@lovrabet/rabetbase-cli 2.5.13 → 2.6.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -17
- package/lib/api/api-doc.js +3 -1
- package/lib/api/api-group.js +3 -1
- package/lib/api/fetch-model-list.js +1 -1
- package/lib/api/generate-api-file.js +8 -1
- package/lib/api/generate-sdk-config-file.js +1 -1
- package/lib/api/legacy-api-file.js +2 -1
- package/lib/api/model-registry-file.js +11 -1
- package/lib/api/model-registry-scaffold.js +2 -1
- package/lib/api/model-source.js +3 -1
- package/lib/auth/auth-server-ui.js +2 -1
- package/lib/auth/auth-server.js +5 -1
- package/lib/auth/constant.js +1 -1
- package/lib/auth/get-cookie.js +1 -1
- package/lib/auth/get-session-user.js +1 -1
- package/lib/auth/is-session-valid.js +1 -1
- package/lib/auth/login-success-html.js +3 -1
- package/lib/auth/logout.js +1 -1
- package/lib/cli-flags.js +1 -1
- package/lib/cli.js +5 -1
- package/lib/commands/api/generate.js +4 -1
- package/lib/commands/api/index.js +1 -1
- package/lib/commands/api/list.js +2 -1
- package/lib/commands/api/pull.js +10 -1
- package/lib/commands/api/shared.js +1 -1
- package/lib/commands/app/detail.js +1 -1
- package/lib/commands/app/index.js +1 -1
- package/lib/commands/app/list.js +5 -1
- package/lib/commands/app/members-list.js +1 -1
- package/lib/commands/app/remote-directory.js +1 -1
- package/lib/commands/app/shared.js +4 -1
- package/lib/commands/app-config/delete.js +2 -1
- package/lib/commands/app-config/get.js +2 -1
- package/lib/commands/app-config/index.js +1 -1
- package/lib/commands/app-config/list.js +2 -1
- package/lib/commands/app-config/set.js +3 -1
- package/lib/commands/app-config/shared.d.ts +9 -2
- package/lib/commands/app-config/shared.js +6 -1
- package/lib/commands/auth/index.js +1 -1
- package/lib/commands/bff/create.js +11 -1
- package/lib/commands/bff/delete.js +6 -1
- package/lib/commands/bff/detail.js +1 -1
- package/lib/commands/bff/index.js +1 -1
- package/lib/commands/bff/list.js +1 -1
- package/lib/commands/bff/logs.js +4 -1
- package/lib/commands/bff/pull.js +22 -1
- package/lib/commands/bff/push.js +16 -1
- package/lib/commands/bff/status.js +3 -1
- package/lib/commands/cli-skill/index.js +2 -1
- package/lib/commands/cli-update.js +7 -1
- package/lib/commands/codegen/index.js +1 -1
- package/lib/commands/codegen/sdk.js +1 -1
- package/lib/commands/codegen/sql.js +1 -1
- package/lib/commands/common/app-registry.js +4 -1
- package/lib/commands/common/app-selector.js +4 -1
- package/lib/commands/common/async-task.js +2 -1
- package/lib/commands/common/dry-run.js +1 -1
- package/lib/commands/common/flags.js +3 -1
- package/lib/commands/common/local-file.js +1 -1
- package/lib/commands/common/validate.js +1 -1
- package/lib/commands/config/delete.js +2 -1
- package/lib/commands/config/get.js +1 -1
- package/lib/commands/config/index.js +1 -1
- package/lib/commands/config/init.js +5 -1
- package/lib/commands/config/list.js +1 -1
- package/lib/commands/config/set.js +4 -1
- package/lib/commands/config/shared.js +2 -1
- package/lib/commands/dataset/batch-design.js +9 -1
- package/lib/commands/dataset/business-group-update.js +10 -1
- package/lib/commands/dataset/business-groups.js +1 -1
- package/lib/commands/dataset/capability.js +3 -1
- package/lib/commands/dataset/cross-relation-create.js +2 -1
- package/lib/commands/dataset/cross-relation-delete.js +1 -1
- package/lib/commands/dataset/cross-relation-list.js +2 -1
- package/lib/commands/dataset/cross-relation-shared.js +10 -1
- package/lib/commands/dataset/cross-relation-update.js +2 -1
- package/lib/commands/dataset/delete.js +6 -1
- package/lib/commands/dataset/design-context.js +1 -1
- package/lib/commands/dataset/design-start.js +1 -1
- package/lib/commands/dataset/design-status.js +1 -1
- package/lib/commands/dataset/design-sync-retry.js +1 -1
- package/lib/commands/dataset/design-sync-status.js +1 -1
- package/lib/commands/dataset/design-validate.js +1 -1
- package/lib/commands/dataset/detail.js +5 -1
- package/lib/commands/dataset/extend-update.js +7 -1
- package/lib/commands/dataset/field-restore.js +7 -1
- package/lib/commands/dataset/field-update.js +7 -1
- package/lib/commands/dataset/generate.js +19 -1
- package/lib/commands/dataset/index.js +3 -1
- package/lib/commands/dataset/list.js +2 -1
- package/lib/commands/dataset/operations.js +2 -1
- package/lib/commands/dataset/relation-audit.js +7 -1
- package/lib/commands/dataset/relation-create.js +3 -1
- package/lib/commands/dataset/relation-delete.js +3 -1
- package/lib/commands/dataset/relation-shared.js +21 -1
- package/lib/commands/dataset/relation-update.js +4 -1
- package/lib/commands/dataset/relations.js +7 -1
- package/lib/commands/dataset/rename.js +4 -1
- package/lib/commands/dataset/restore.js +7 -1
- package/lib/commands/dataset/user-deleted-field-list.js +3 -1
- package/lib/commands/db/analysis-batching.js +3 -1
- package/lib/commands/db/analyze-batch-plan.js +2 -1
- package/lib/commands/db/analyze-cancel.js +1 -1
- package/lib/commands/db/analyze-start.js +3 -1
- package/lib/commands/db/analyze-status.js +6 -1
- package/lib/commands/db/create.js +4 -1
- package/lib/commands/db/cross-db-analysis-shared.js +3 -1
- package/lib/commands/db/cross-db-analyze-latest.js +1 -1
- package/lib/commands/db/cross-db-analyze-start.js +2 -1
- package/lib/commands/db/cross-db-analyze-status.js +1 -1
- package/lib/commands/db/delete.js +3 -1
- package/lib/commands/db/detail.js +1 -1
- package/lib/commands/db/diff-refresh-start.js +1 -1
- package/lib/commands/db/diff-refresh-status.js +2 -1
- package/lib/commands/db/diff.js +3 -1
- package/lib/commands/db/index.js +2 -1
- package/lib/commands/db/list.js +2 -1
- package/lib/commands/db/shared.js +3 -1
- package/lib/commands/db/table-diff-shared.js +2 -1
- package/lib/commands/db/tables.js +2 -1
- package/lib/commands/db/test.js +2 -1
- package/lib/commands/db/update.js +4 -1
- package/lib/commands/deployment/index.js +1 -1
- package/lib/commands/deployment/sync-all.js +3 -1
- package/lib/commands/deployment/sync-jobs.js +2 -1
- package/lib/commands/deployment/sync-status.js +2 -1
- package/lib/commands/doctor.js +12 -1
- package/lib/commands/file/index.js +3 -1
- package/lib/commands/flow/create.js +2 -1
- package/lib/commands/flow/detail.js +3 -1
- package/lib/commands/flow/index.js +1 -1
- package/lib/commands/flow/list.js +2 -1
- package/lib/commands/flow/page-list.js +2 -1
- package/lib/commands/flow/publish.js +2 -1
- package/lib/commands/flow/runtime-resources-shared.js +3 -1
- package/lib/commands/flow/runtime-role-list.js +2 -1
- package/lib/commands/flow/runtime-role-user-list.js +2 -1
- package/lib/commands/flow/runtime-user-search.js +2 -1
- package/lib/commands/flow/shared.js +6 -1
- package/lib/commands/flow/update.js +4 -1
- package/lib/commands/flow/validate.js +2 -1
- package/lib/commands/instant-api-policy/current.js +1 -1
- package/lib/commands/instant-api-policy/index.js +1 -1
- package/lib/commands/instant-api-policy/init.js +2 -1
- package/lib/commands/instant-api-policy/publish.js +5 -1
- package/lib/commands/instant-api-policy/pull.js +2 -1
- package/lib/commands/instant-api-policy/revision.js +1 -1
- package/lib/commands/instant-api-policy/revisions.js +1 -1
- package/lib/commands/instant-api-policy/rollback.js +5 -1
- package/lib/commands/instant-api-policy/shared.js +5 -1
- package/lib/commands/instant-api-policy/validate.js +1 -1
- package/lib/commands/issue/context.js +1 -1
- package/lib/commands/issue/index.js +1 -1
- package/lib/commands/issue/nudge.js +2 -1
- package/lib/commands/issue/report.js +5 -1
- package/lib/commands/kb/create.js +5 -1
- package/lib/commands/kb/delete.js +5 -1
- package/lib/commands/kb/detail.js +1 -1
- package/lib/commands/kb/import-api.d.ts +3 -0
- package/lib/commands/kb/import-api.js +1 -0
- package/lib/commands/kb/import-resume.d.ts +2 -0
- package/lib/commands/kb/import-resume.js +2 -0
- package/lib/commands/kb/import-shared.d.ts +69 -0
- package/lib/commands/kb/import-shared.js +9 -0
- package/lib/commands/kb/import-status.d.ts +2 -0
- package/lib/commands/kb/import-status.js +1 -0
- package/lib/commands/kb/import.d.ts +2 -0
- package/lib/commands/kb/import.js +3 -0
- package/lib/commands/kb/index.js +1 -1
- package/lib/commands/kb/list.js +1 -1
- package/lib/commands/kb/search.js +3 -1
- package/lib/commands/kb/shared.js +9 -1
- package/lib/commands/kb/update.js +7 -1
- package/lib/commands/logs/index.js +2 -1
- package/lib/commands/menu/asset-update.js +8 -1
- package/lib/commands/menu/delete.js +15 -1
- package/lib/commands/menu/external-link-create.js +16 -1
- package/lib/commands/menu/external-link-update.js +10 -1
- package/lib/commands/menu/group-create.js +8 -1
- package/lib/commands/menu/group-update.js +6 -1
- package/lib/commands/menu/index.js +2 -1
- package/lib/commands/menu/list.js +1 -1
- package/lib/commands/menu/move.js +6 -1
- package/lib/commands/menu/regroup-start.js +11 -1
- package/lib/commands/menu/rename.js +9 -1
- package/lib/commands/menu/shared/compare-table.js +2 -1
- package/lib/commands/menu/shared/delete-plan.js +13 -1
- package/lib/commands/menu/shared/facts.js +5 -1
- package/lib/commands/menu/shared/index.js +1 -1
- package/lib/commands/menu/shared/inquirer.js +4 -1
- package/lib/commands/menu/shared/local-pages.js +5 -1
- package/lib/commands/menu/shared/logic.js +3 -1
- package/lib/commands/menu/shared/mutations.js +9 -1
- package/lib/commands/menu/shared/path.js +1 -1
- package/lib/commands/menu/shared/service.js +4 -1
- package/lib/commands/menu/shared/subapp-assets.js +4 -1
- package/lib/commands/menu/shared/sync-core.js +7 -1
- package/lib/commands/menu/shared/types.js +1 -1
- package/lib/commands/menu/shared/update-core.js +8 -1
- package/lib/commands/menu/shared/valid-url.js +1 -1
- package/lib/commands/menu/subapp-assets-status.js +1 -1
- package/lib/commands/menu/subapp-assets-update.js +7 -1
- package/lib/commands/menu/sync.js +7 -1
- package/lib/commands/menu/visibility-update.js +13 -1
- package/lib/commands/metric/contract.d.ts +8 -0
- package/lib/commands/metric/contract.js +5 -0
- package/lib/commands/metric/definition.d.ts +43 -0
- package/lib/commands/metric/definition.js +4 -0
- package/lib/commands/metric/delete.d.ts +2 -0
- package/lib/commands/metric/delete.js +3 -0
- package/lib/commands/metric/detail.d.ts +2 -0
- package/lib/commands/metric/detail.js +1 -0
- package/lib/commands/metric/example.d.ts +2 -0
- package/lib/commands/metric/example.js +1 -0
- package/lib/commands/metric/index.d.ts +2 -0
- package/lib/commands/metric/index.js +1 -0
- package/lib/commands/metric/list.d.ts +2 -0
- package/lib/commands/metric/list.js +2 -0
- package/lib/commands/metric/publication-diff.d.ts +8 -0
- package/lib/commands/metric/publication-diff.js +1 -0
- package/lib/commands/metric/publish.d.ts +2 -0
- package/lib/commands/metric/publish.js +4 -0
- package/lib/commands/metric/schema.d.ts +2 -0
- package/lib/commands/metric/schema.js +1 -0
- package/lib/commands/metric/shared.d.ts +14 -0
- package/lib/commands/metric/shared.js +2 -0
- package/lib/commands/metric/validate.d.ts +2 -0
- package/lib/commands/metric/validate.js +1 -0
- package/lib/commands/notification/config-create.js +4 -1
- package/lib/commands/notification/config-delete.js +4 -1
- package/lib/commands/notification/config-list.js +2 -1
- package/lib/commands/notification/config-update.js +4 -1
- package/lib/commands/notification/index.js +1 -1
- package/lib/commands/notification/shared.js +18 -1
- package/lib/commands/ocr/index.js +4 -1
- package/lib/commands/page/create.js +6 -1
- package/lib/commands/page/custom/detail.js +2 -1
- package/lib/commands/page/custom/list.js +2 -1
- package/lib/commands/page/custom/publish.js +3 -1
- package/lib/commands/page/custom/shared.js +3 -1
- package/lib/commands/page/custom/syntax.js +2 -1
- package/lib/commands/page/custom/update.js +3 -1
- package/lib/commands/page/data-list-status.js +2 -1
- package/lib/commands/page/generate-start.js +5 -1
- package/lib/commands/page/generate-status.js +4 -1
- package/lib/commands/page/index.js +2 -1
- package/lib/commands/page/pull.js +6 -1
- package/lib/commands/page/push.js +11 -1
- package/lib/commands/page/relation-audit.js +15 -1
- package/lib/commands/page/restore.js +5 -1
- package/lib/commands/page/shared.js +16 -1
- package/lib/commands/page/sync.js +2 -1
- package/lib/commands/project/api-architecture-upgrade.js +11 -1
- package/lib/commands/project/create/enhanced-guided-create.js +2 -1
- package/lib/commands/project/create/format-elapsed.js +1 -1
- package/lib/commands/project/create/main.js +13 -1
- package/lib/commands/project/create/materialize-project-template.js +12 -1
- package/lib/commands/project/create/project-name.js +1 -1
- package/lib/commands/project/create/project-template-archive.js +5 -1
- package/lib/commands/project/create/project-template-path.js +1 -1
- package/lib/commands/project/create/use-copy-project-template.js +2 -1
- package/lib/commands/project/create/use-format-code.js +1 -1
- package/lib/commands/project/create/use-install-dependencies.js +1 -1
- package/lib/commands/project/domain-routing-sync.js +1 -1
- package/lib/commands/project/index.js +4 -1
- package/lib/commands/project/upgrade.js +7 -1
- package/lib/commands/registry.js +10 -1
- package/lib/commands/role/delete.js +2 -1
- package/lib/commands/role/detail.js +1 -1
- package/lib/commands/role/index.js +1 -1
- package/lib/commands/role/list.js +2 -1
- package/lib/commands/role/shared.js +8 -1
- package/lib/commands/role/update.js +3 -1
- package/lib/commands/role/user-add.js +2 -1
- package/lib/commands/role/user-remove.js +2 -1
- package/lib/commands/role/user-resolve.js +1 -1
- package/lib/commands/rule/get.js +1 -1
- package/lib/commands/rule/index.js +1 -1
- package/lib/commands/rule/list.js +1 -1
- package/lib/commands/rule/set.js +7 -1
- package/lib/commands/rule/shared.js +4 -1
- package/lib/commands/run/index.js +5 -1
- package/lib/commands/schema.js +1 -1
- package/lib/commands/sql/create.js +7 -1
- package/lib/commands/sql/delete.js +4 -1
- package/lib/commands/sql/detail.js +1 -1
- package/lib/commands/sql/exec.js +1 -1
- package/lib/commands/sql/index.js +1 -1
- package/lib/commands/sql/list.js +2 -1
- package/lib/commands/sql/pull.js +10 -1
- package/lib/commands/sql/push.js +9 -1
- package/lib/commands/sql/shared.js +5 -1
- package/lib/commands/sql/status.js +3 -1
- package/lib/commands/sql/validate.js +5 -1
- package/lib/commands/task/index.js +1 -1
- package/lib/commands/task/status.js +2 -1
- package/lib/commands/tenant/index.js +1 -1
- package/lib/commands/tenant/members-list.js +2 -1
- package/lib/commands/tenant/shared.js +2 -1
- package/lib/commands/user-account/dingding-sandbox-bind.js +2 -1
- package/lib/commands/user-account/feishu-bind.js +2 -1
- package/lib/commands/user-account/index.js +1 -1
- package/lib/commands/workspace/add.js +1 -1
- package/lib/commands/workspace/index.js +7 -1
- package/lib/commands/workspace/remove.js +1 -1
- package/lib/config/domain-config.js +8 -1
- package/lib/config/project-domain-routing.js +3 -1
- package/lib/config/region-config.js +2 -1
- package/lib/config/schema.js +7 -1
- package/lib/constant/cdn.js +2 -1
- package/lib/constant/cli.js +8 -1
- package/lib/constant/defaults.js +1 -1
- package/lib/constant/domain.js +4 -1
- package/lib/constant/env.js +1 -1
- package/lib/constant/output.js +1 -1
- package/lib/constant/paths.js +1 -1
- package/lib/constant/region.js +1 -1
- package/lib/constant/risk.js +1 -1
- package/lib/constant/routing-profile.js +1 -1
- package/lib/context/app-resolver.js +7 -1
- package/lib/context/auth-resolver.js +1 -1
- package/lib/context/config-loader.js +7 -1
- package/lib/context.js +9 -1
- package/lib/core/alias-resolver.js +5 -1
- package/lib/core/api-client.d.ts +14 -7
- package/lib/core/api-client.js +69 -1
- package/lib/core/bff/config.js +1 -1
- package/lib/core/bff/file-system.js +6 -1
- package/lib/core/bff/hash.js +1 -1
- package/lib/core/bff/hook-directory.js +9 -1
- package/lib/core/bff/lock.js +2 -1
- package/lib/core/bff/types.js +1 -1
- package/lib/core/bff/utils.js +3 -1
- package/lib/core/cross-db-analysis.js +1 -1
- package/lib/core/cross-db-relation.js +1 -1
- package/lib/core/db-resolver.js +2 -1
- package/lib/core/flow-config.js +49 -1
- package/lib/core/instant-api-policy/config.js +7 -1
- package/lib/core/instant-api-policy/endpoints.js +1 -1
- package/lib/core/kb-management-client.d.ts +11 -0
- package/lib/core/kb-management-client.js +4 -1
- package/lib/core/kb-search-client.js +3 -1
- package/lib/core/page/file-system.js +2 -1
- package/lib/core/page/hash.js +1 -1
- package/lib/core/page/lock.js +2 -1
- package/lib/core/page/lr-smart-jsx.js +4 -1
- package/lib/core/page/types.js +1 -1
- package/lib/core/sql-index-auditor.js +14 -1
- package/lib/core/sql-sync/config.js +1 -1
- package/lib/core/sql-sync/file-system.js +3 -1
- package/lib/core/sql-sync/hash.js +1 -1
- package/lib/core/sql-sync/lock.js +2 -1
- package/lib/core/sql-sync/types.js +1 -1
- package/lib/core/sql-sync/utils.js +2 -1
- package/lib/core/sql-validator.js +15 -1
- package/lib/errors.js +3 -1
- package/lib/framework/build-all-flags.js +1 -1
- package/lib/framework/error-output.js +1 -1
- package/lib/framework/explicit-yes.js +1 -1
- package/lib/framework/flags.js +1 -1
- package/lib/framework/help.js +2 -1
- package/lib/framework/index.js +1 -1
- package/lib/framework/output.js +2 -1
- package/lib/framework/response.js +1 -1
- package/lib/framework/runner-alias.js +2 -1
- package/lib/framework/runner.js +9 -1
- package/lib/framework/schema-export.js +1 -1
- package/lib/framework/supported-flags.js +2 -1
- package/lib/framework/types.js +1 -1
- package/lib/generated/build-info.d.ts +4 -4
- package/lib/generated/build-info.js +1 -1
- package/lib/generated/official-routing.js +3 -1
- package/lib/generated/routing-contract.js +1 -1
- package/lib/help.js +1 -1
- package/lib/runtime/confirmation.js +2 -1
- package/lib/runtime/event.js +1 -1
- package/lib/runtime/index.js +4 -1
- package/lib/runtime/queue.js +1 -1
- package/lib/runtime/resolve.js +2 -1
- package/lib/runtime/types.js +1 -1
- package/lib/services/dataset-design/checkpoint.js +2 -1
- package/lib/services/dataset-design/commands.js +14 -1
- package/lib/services/dataset-design/contract.js +8 -1
- package/lib/skills/builtin-skill.js +8 -1
- package/lib/skills/install-updated-skill.d.ts +8 -0
- package/lib/skills/install-updated-skill.js +3 -0
- package/lib/skills/local-skills-installer.d.ts +2 -0
- package/lib/skills/local-skills-installer.js +1 -0
- package/lib/skills/main.js +2 -1
- package/lib/skills/npx-skills-add.d.ts +6 -6
- package/lib/skills/npx-skills-add.js +5 -1
- package/lib/skills/skill-presence.d.ts +1 -30
- package/lib/skills/skill-presence.js +2 -1
- package/lib/telemetry/cli-command-trace.js +2 -1
- package/lib/telemetry/cli-help-trace.js +1 -1
- package/lib/telemetry/ensure-cli-otel-config.js +1 -1
- package/lib/telemetry/register-otel-exit-shutdown.js +1 -1
- package/lib/telemetry/send-cli-trace-log.js +1 -1
- package/lib/types/index.js +1 -1
- package/lib/utils/ai_config.js +3 -1
- package/lib/utils/apply-jq-filter.js +1 -1
- package/lib/utils/cdn-config.js +1 -1
- package/lib/utils/check-sdk-version.js +5 -1
- package/lib/utils/cli-version-check.js +4 -1
- package/lib/utils/cli-version-policy.js +3 -1
- package/lib/utils/config.js +1 -1
- package/lib/utils/entity-with-id.js +1 -1
- package/lib/utils/file-utils.js +1 -1
- package/lib/utils/guides-cdn.js +3 -1
- package/lib/utils/http-client.js +2 -1
- package/lib/utils/is-non-interactive.js +1 -1
- package/lib/utils/logger.js +3 -1
- package/lib/utils/params.js +1 -1
- package/lib/utils/platform.js +1 -1
- package/lib/utils/sleep.js +1 -1
- package/lib/utils/template-replacer.js +5 -1
- package/lib/utils/update-notice.js +3 -1
- package/lib/utils/version.js +1 -1
- package/lib/utils/with-active-cookie.js +1 -1
- package/lib/utils/write-cli-side-channel.js +1 -1
- package/package.json +10 -7
- package/skills/rabetbase/SKILL.md +11 -7
- package/skills/rabetbase/guides/backend-function.md +3 -1
- package/skills/rabetbase/guides/data-api-guidelines.md +1 -1
- package/skills/rabetbase/guides/frontend-development.md +1 -0
- package/skills/rabetbase/guides/metric-development.md +185 -0
- package/skills/rabetbase/references/rabetbase-app-config.md +4 -3
- package/skills/rabetbase/references/rabetbase-cli-skill-install.md +5 -5
- package/skills/rabetbase/references/rabetbase-dataset-design.md +1 -1
- package/skills/rabetbase/references/rabetbase-kb.md +16 -0
- package/skills/rabetbase/references/rabetbase-metric.md +119 -0
- package/skills/rabetbase/references/rabetbase-update.md +7 -5
- package/skills/rabetbase-dataset-generation/SKILL.md +1 -1
- package/skills/rabetbase-dataset-generation/references/workflow.md +1 -1
- package/skills/rabetbase-metrics-generation/SKILL.md +22 -0
- package/skills/rabetbase-metrics-generation/references/verification.md +19 -0
- package/skills/rabetbase-metrics-generation/references/workflow.md +41 -0
- package/skills/rabetbase-metrics-generation/templates/statistics-delivery.md +11 -0
- package/skills/rabetbase-page-generation/SKILL.md +1 -1
- package/skills/rabetbase-page-generation/references/generation.md +1 -1
- package/skills/rabetbase.manifest.json +5 -3
- package/templates/metrics/definition.json +78 -0
- package/templates/metrics/metric-definition.schema.json +136 -0
- package/lib/postinstall.d.ts +0 -3
- package/lib/postinstall.js +0 -1
- package/scripts/postinstall.mjs +0 -24
|
@@ -10,8 +10,8 @@ export declare const NPX_FLAG_YES: "-y";
|
|
|
10
10
|
export declare const SKILLS_FLAG_GLOBAL: "-g";
|
|
11
11
|
/** `skills add` 的非交互确认短参数 */
|
|
12
12
|
export declare const SKILLS_FLAG_YES: "-y";
|
|
13
|
-
/**
|
|
14
|
-
export declare const NPX_SKILLS_CLI: "skills@
|
|
13
|
+
/** 独立安装提示使用与 package.json 相同的固定版本;内部执行使用本地依赖。 */
|
|
14
|
+
export declare const NPX_SKILLS_CLI: "skills@1.8.1";
|
|
15
15
|
/** `skills` 子命令:add */
|
|
16
16
|
export declare const NPX_SKILLS_SUBCOMMAND_ADD: "add";
|
|
17
17
|
/** `--skill` 长选项名 */
|
|
@@ -56,7 +56,7 @@ export interface RunNpxSkillsAddResult {
|
|
|
56
56
|
count: number;
|
|
57
57
|
output: string;
|
|
58
58
|
};
|
|
59
|
-
/**
|
|
59
|
+
/** 未执行安装器(RABETBASE_SKIP_NPX_SKILLS=1),仅用于测试或离线假定已安装 */
|
|
60
60
|
skipped?: boolean;
|
|
61
61
|
}
|
|
62
62
|
export interface RunNpxSkillsAddOptions {
|
|
@@ -75,13 +75,13 @@ export interface RunNpxSkillsAddOptions {
|
|
|
75
75
|
* 失败分类。优先使用 OS / Node 层稳定信号与本地可解析的安装事实。
|
|
76
76
|
* 外部输出仅识别安装器的 `Failed to install N` 汇总,其余文案只作为诊断信息。
|
|
77
77
|
*/
|
|
78
|
-
export type NpxSkillsErrorCode = "
|
|
78
|
+
export type NpxSkillsErrorCode = "NODE_NOT_FOUND" | "INSTALLER_UNAVAILABLE" | "PERMISSION_DENIED" | "SPAWN_FAILED" | "CHILD_TERMINATED" | "CHILD_EXIT_NONZERO" | "INSTALL_PARTIAL" | "SKILL_NOT_INSTALLED";
|
|
79
79
|
/**
|
|
80
|
-
* 若设置 RABETBASE_SKIP_NPX_SKILLS=1
|
|
80
|
+
* 若设置 RABETBASE_SKIP_NPX_SKILLS=1,跳过执行(供离线/测试注入;对项目级与全局安装均生效)
|
|
81
81
|
*/
|
|
82
82
|
export declare function shouldSkipNpxSkillsAdd(): boolean;
|
|
83
83
|
/**
|
|
84
|
-
*
|
|
84
|
+
* 在项目根目录通过本地安装器执行与独立安装提示等价的调用
|
|
85
85
|
*
|
|
86
86
|
* @param projectRoot 项目根目录
|
|
87
87
|
* @param options.stdio - inherit(交互式终端)或 pipe(CI)
|
|
@@ -1 +1,5 @@
|
|
|
1
|
-
|
|
1
|
+
import{execaSync}from"execa";import{resolveLocalSkillsInstaller}from"../skills/local-skills-installer.js";import{resolveInstalledSkill}from"../skills/skill-presence.js";export const NPX_FLAG_YES="-y";export const SKILLS_FLAG_GLOBAL="-g";export const SKILLS_FLAG_YES="-y";export const NPX_SKILLS_CLI="skills@1.8.1";export const NPX_SKILLS_SUBCOMMAND_ADD="add";export const NPX_SKILLS_FLAG_SKILL="--skill";export const RABETBASE_SKILL_SOURCE="lovrabet/rabetbase";export const RABETBASE_GLOBAL_SKILL_NAME="rabetbase";export const RABETBASE_SKILL_GIT_SOURCE="git@codeup.aliyun.com:yuntoo/open/rabetbase-cli.git";export function resolveGlobalSkillName(source){switch(source.trim()){case RABETBASE_SKILL_SOURCE:case RABETBASE_SKILL_GIT_SOURCE:return RABETBASE_GLOBAL_SKILL_NAME;default:return undefined}}export function buildNpxSkillsAddArgv(skillName){const args=[NPX_FLAG_YES,NPX_SKILLS_CLI,NPX_SKILLS_SUBCOMMAND_ADD,RABETBASE_SKILL_SOURCE];if(skillName){args.push(NPX_SKILLS_FLAG_SKILL,skillName)}
|
|
2
|
+
return args}export const NPX_SKILLS_ADD_COMMAND_LINE=["npx",...buildNpxSkillsAddArgv()].join(" ");export const NPX_SKILLS_ADD_GLOBAL_COMMAND_LINE=["npx",NPX_FLAG_YES,NPX_SKILLS_CLI,NPX_SKILLS_SUBCOMMAND_ADD,RABETBASE_SKILL_SOURCE,SKILLS_FLAG_GLOBAL,SKILLS_FLAG_YES].join(" ");const CHILD_OUTPUT_MAX_BUFFER=16*1024*1024;function failure(code,status,detail){return{ok:false,status:status,code:code,error:`[${code}] ${detail}`}}function execaOptions(projectRoot,stdio){const env={...process.env,DISABLE_TELEMETRY:"1"};delete env.npm_config_global;delete env.NPM_CONFIG_GLOBAL;return{cwd:projectRoot,stdio:stdio,env:env,extendEnv:false,shell:false,reject:false,...stdio==="pipe"?{maxBuffer:CHILD_OUTPUT_MAX_BUFFER}:{}}}function normalizeExecaResult(result,skillName,presenceOptions){const output=[result.stdout?String(result.stdout):"",result.stderr?String(result.stderr):""].filter(Boolean).join("\n").trim();const status=result.exitCode??null;if(result.code){
|
|
3
|
+
const code=result.code==="ENOENT"?"NODE_NOT_FOUND":result.code==="EPERM"||result.code==="EACCES"?"PERMISSION_DENIED":"SPAWN_FAILED";return failure(code,status,result.shortMessage??result.message??result.code)}if(result.signal){return failure("CHILD_TERMINATED",status,`Skills installer terminated by signal ${result.signal}`)}if(result.failed&&status===null){return failure("SPAWN_FAILED",status,result.shortMessage??result.message??"Skills installer failed to start")}if(status!==0){return failure("CHILD_EXIT_NONZERO",status,output||result.shortMessage||`exit ${status??"unknown"}`)}const presence=skillName?resolveInstalledSkill(skillName,presenceOptions):undefined;const failedCount=output.match(/Failed to install\s+(\d+)/i);if(failedCount&&Number(failedCount[1])>0){const detail=`Installer reported ${failedCount[1]} failed target(s)${output?`:\n${output}`:""}`;if(presence?.state==="present"){return{ok:true,status:0,partialFailure:{count:Number(failedCount[1]),output:output}}}
|
|
4
|
+
return failure("INSTALL_PARTIAL",0,detail)}if(presence){if(presence.state==="absent"){return failure("SKILL_NOT_INSTALLED",0,`Skill "${skillName}" not listed as installed by Skills CLI`)}if(presence.state==="unverifiable"){console.warn(`! Could not verify "${skillName}" install state: ${presence.reason}`)}}return{ok:true,status:0}}export function shouldSkipNpxSkillsAdd(){return process.env.RABETBASE_SKIP_NPX_SKILLS==="1"}export function runNpxSkillsAdd(projectRoot,options){if(shouldSkipNpxSkillsAdd()){return{ok:true,status:0,skipped:true}}const stdio=options?.stdio??"inherit";let installer;try{installer=resolveLocalSkillsInstaller()}catch(error){return failure("INSTALLER_UNAVAILABLE",null,error instanceof Error?error.message:String(error))}const args=[installer,...buildNpxSkillsAddArgv(options?.skill).slice(2)];const displayCmd=["skills",...args.slice(1)].join(" ");console.log(`* ${displayCmd}`);const result=execaSync(process.execPath,args,execaOptions(projectRoot,stdio))
|
|
5
|
+
;return normalizeExecaResult(result)}export function runNpxSkillsAddGlobal(projectRoot,source,options){if(shouldSkipNpxSkillsAdd()){return{ok:true,status:0,skipped:true}}let installer;try{installer=resolveLocalSkillsInstaller()}catch(error){return failure("INSTALLER_UNAVAILABLE",null,error instanceof Error?error.message:String(error))}const args=[installer,NPX_SKILLS_SUBCOMMAND_ADD,source,SKILLS_FLAG_GLOBAL,SKILLS_FLAG_YES];console.log(`* ${["skills",...args.slice(1)].join(" ")}`);const result=execaSync(process.execPath,args,execaOptions(projectRoot,"pipe"));const normalized=normalizeExecaResult(result,options?.expectedSkillName??resolveGlobalSkillName(source),options?.presence);if(options?.stdio!=="pipe"&&!normalized.partialFailure){const output=[result.stdout,result.stderr].filter(Boolean).join("\n").trim();if(output)console.log(output)}return normalized}
|
|
@@ -1,22 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 全局 Skill 安装事实解析(与外部 skills CLI 解耦)
|
|
3
|
-
*
|
|
4
|
-
* 判定原则:只依据可信度较高的信号,且区分「确认未安装」与「无法确认」。
|
|
5
|
-
* - 产物探测:消费方真正解析的 `<globalSkillsDir>/<name>/SKILL.md`
|
|
6
|
-
* - 安装记账:skills CLI 自己维护的 `~/.agents/.skill-lock.json`
|
|
7
|
-
*
|
|
8
|
-
* 目录布局归外部工具所有,因此布局假设失效时必须落到 `unverifiable`(放行 + 说明原因),
|
|
9
|
-
* 不能落到 `absent`(判失败)。只有产物与记账两个来源都表明没装,才是 `absent`。
|
|
10
|
-
*/
|
|
11
|
-
/** skills CLI 安装记账文件(相对 HOME) */
|
|
12
|
-
export declare const SKILL_LOCK_RELATIVE_PATH: string;
|
|
13
|
-
/** 已知的全局 Skill 目录(相对 HOME),按探测优先级排列 */
|
|
14
|
-
export declare const GLOBAL_SKILLS_DIR_RELATIVE_PATHS: string[];
|
|
15
|
-
/**
|
|
16
|
-
* 全局 Skill 的安装事实。
|
|
17
|
-
*
|
|
18
|
-
* `unverifiable` 是刻意保留的第三态:表示本地假设不足以判断,调用方应放行而非报错。
|
|
19
|
-
*/
|
|
20
1
|
export type SkillPresence = {
|
|
21
2
|
state: "present";
|
|
22
3
|
path: string;
|
|
@@ -28,17 +9,7 @@ export type SkillPresence = {
|
|
|
28
9
|
reason: string;
|
|
29
10
|
};
|
|
30
11
|
export interface ResolveSkillPresenceOptions {
|
|
31
|
-
/**
|
|
32
|
-
globalSkillsDirs?: string[];
|
|
33
|
-
/** 覆盖 skills CLI 安装记账文件路径 */
|
|
34
|
-
lockFile?: string;
|
|
35
|
-
/** 覆盖 HOME,仅用于测试 */
|
|
12
|
+
/** Override the user home for isolated verification only. */
|
|
36
13
|
home?: string;
|
|
37
14
|
}
|
|
38
|
-
/**
|
|
39
|
-
* 解析指定全局 Skill 当前是否可被消费方解析到。
|
|
40
|
-
*
|
|
41
|
-
* @param skillName 全局 Skill 名(目录名),如 `rabetbase`
|
|
42
|
-
* @returns `present` / `absent` / `unverifiable`
|
|
43
|
-
*/
|
|
44
15
|
export declare function resolveInstalledSkill(skillName: string, options?: ResolveSkillPresenceOptions): SkillPresence;
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{spawnSync}from"node:child_process";import{isAbsolute,join}from"node:path";import{resolveLocalSkillsInstaller}from"../skills/local-skills-installer.js";export function resolveInstalledSkill(skillName,options){try{const env={...process.env,DISABLE_TELEMETRY:"1",DO_NOT_TRACK:"1",...options?.home?{HOME:options.home,USERPROFILE:options.home}:{}};const result=spawnSync(process.execPath,[resolveLocalSkillsInstaller(),"list","-g","--json"],{env:env,encoding:"utf8",shell:false,timeout:3e4,maxBuffer:16*1024*1024});if(result.error||result.status!==0){throw new Error(result.error?.message||result.stderr?.trim()||"Skills CLI listing failed")}const rows=JSON.parse(result.stdout);if(!Array.isArray(rows)||rows.some(row=>!row||typeof row.name!=="string"||row.scope!=="global")){throw new Error("Unsupported Skills CLI listing response")}const matches=rows.filter(row=>row.name===skillName);if(matches.length===0||matches.every(row=>row.status==="missing"&&row.path===null)){return{state:"absent",
|
|
2
|
+
checked:[]}}if(matches.some(row=>!["tracked","untracked","modified"].includes(row.status)||typeof row.path!=="string"||!isAbsolute(row.path))){throw new Error(`Skills CLI returned an invalid installation path or status for "${skillName}"`)}const paths=[...new Set(matches.map(row=>row.path))];if(paths.length!==1)throw new Error(`Skills CLI returned multiple installation paths for "${skillName}"`);return{state:"present",path:join(paths[0],"SKILL.md")}}catch(error){return{state:"unverifiable",reason:error instanceof Error?error.message:String(error)}}}
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{sendCliTraceLog}from"../telemetry/send-cli-trace-log.js";import{getCliVersion}from"../utils/version.js";const SENSITIVE_PATTERNS=[/cookie/i,/token/i,/password/i,/passwd/i,/secret/i,/auth/i,/session/i,/credential/i,/^value$/i];function isSensitiveKey(key){return SENSITIVE_PATTERNS.some(p=>p.test(key))}function sanitizeFlags(flags){const safe={};for(const[key,value]of Object.entries(flags)){if(isSensitiveKey(key)){safe[key]=value!=null&&value!==""?"[REDACTED]":value}else{safe[key]=value}}return safe}export async function reportCommandTrace(params){if(params.service==="issue"&¶ms.command==="report")return;try{const safeFlags=sanitizeFlags(params.flags);await sendCliTraceLog({spanName:"rabetbase.command",logData:{"command.cli_version":getCliVersion(),"command.service":params.service,"command.name":params.command,"command.flags":JSON.stringify(safeFlags),...params.durationMs!=null?{"command.duration_ms":params.durationMs}:{},...params.error?{
|
|
2
|
+
"command.error":params.error instanceof Error?params.error.message:String(params.error)}:{}}})}catch{}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{sendCliTraceLog}from"../telemetry/send-cli-trace-log.js";export async function reportCliHelpTrace(kind,options){try{await sendCliTraceLog({spanName:"cli.help",logData:{"rabetbase.help.kind":kind,...options?.service&&{"rabetbase.help.service":options.service}}})}catch(err){console.error("Failed to report CLI help trace:",err)}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{VERSION,GIT_COMMIT}from"../generated/build-info.js";import{getSessionUserInfo}from"../auth/get-session-user.js";import{setServiceConfig,setUserContext}from"@lovrabet/otel-logger";import{NPM_PACKAGE_NAME}from"../constant/cli.js";import{getConfigAppCode}from"../utils/config.js";let cliOtelTraceInitialized=false;export async function ensureCliOtelTraceConfig(){const sessionInfo=await getSessionUserInfo();if(!cliOtelTraceInitialized){const u=sessionInfo?.user;setServiceConfig({serviceName:NPM_PACKAGE_NAME,serviceVersion:GIT_COMMIT!=="unknown"?`${VERSION}+${GIT_COMMIT}`:VERSION,serviceEnv:process.env.RABETBASE_ENV??(process.env.RABETBASE_E2E_DAILY==="1"?"daily":"production")});setUserContext({id:u?.id,username:u?.username,nickname:u?.nickname,email:u?.email,tenantCode:u?.tenant?.tenant_code,appCode:getConfigAppCode()});cliOtelTraceInitialized=true}return sessionInfo}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{shutdownTraces}from"@lovrabet/otel-logger";let shutdownPromise=null;export async function flushOtelNodeIfUsed(){if(shutdownPromise){return shutdownPromise}shutdownPromise=(async()=>{try{await shutdownTraces()}catch{}})();return shutdownPromise}export function registerOtelShutdownOnExit(){process.once("beforeExit",()=>{void flushOtelNodeIfUsed()});const onSignal=()=>{void flushOtelNodeIfUsed().then(()=>process.exit(0))};process.once("SIGINT",onSignal);process.once("SIGTERM",onSignal)}export async function exitWithOtelShutdown(exitCode){await flushOtelNodeIfUsed();process.exit(exitCode)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{sendTraceLog}from"@lovrabet/otel-logger";import{ensureCliOtelTraceConfig}from"../telemetry/ensure-cli-otel-config.js";import{getCliVersion}from"../utils/version.js";const DEFAULT_TRACE_NAME="rabetbase-cli";export async function sendCliTraceLog(params){await ensureCliOtelTraceConfig();sendTraceLog({traceName:params.traceName??DEFAULT_TRACE_NAME,version:params.version??getCliVersion(),spanName:params.spanName,eventType:"manual",logData:params.logData,...params.traceparent&&{traceparent:params.traceparent}})}
|
package/lib/types/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{};
|
|
1
|
+
export{};
|
package/lib/utils/ai_config.js
CHANGED
|
@@ -1 +1,3 @@
|
|
|
1
|
-
|
|
1
|
+
export const CORE_IDE_CONFIGS={cursor:{name:"Cursor",description:"Cursor IDE",folders:[".cursorrules",".cursor"],files:[{type:"file",path:".cursor/skills/rabetbase.md"}]},windsurf:{name:"Windsurf",description:"Windsurf IDE",folders:[".windsurf"],files:[{type:"file",path:".windsurf/workflows/rabetbase.md"}]},claude:{name:"Claude Code",description:"Claude Code",folders:[".claude"],files:[{type:"file",path:".claude/skills/lovrabet/SKILL.md"}]},cline:{name:"Cline",description:"Cline IDE",folders:[".cline"],files:[{type:"file",path:".cline/skills/lovrabet/SKILL.md"}]},codex:{name:"Codex",description:"Codex IDE",folders:[".codex"],files:[{type:"file",path:".codex/skills/lovrabet/SKILL.md"}]},opencode:{name:"OpenCode",description:"OpenCode IDE",folders:[".opencode"],files:[{type:"file",path:".opencode/skills/lovrabet/SKILL.md"}]},qoder:{name:"Qoder",description:"Qoder IDE",folders:[".qoder"],files:[{type:"file",path:".qoder/rules/rabetbase.md"},{type:"file",
|
|
2
|
+
path:".qoder/skills/lovrabet/SKILL.md"}]},codebuddy:{name:"CodeBuddy",description:"CodeBuddy IDE",folders:[".codebuddy"],files:[{type:"file",path:".codebuddy/skills/lovrabet/SKILL.md"}]},trae:{name:"Trae",description:"Trae IDE",folders:[".trae"],files:[{type:"file",path:".trae/skills/lovrabet/SKILL.md"}]}};export const IDE_CONFIGS={...CORE_IDE_CONFIGS,agent:{name:"Other (generic template)",description:"Generic template fallback",folders:[".agent"],files:[{type:"file",path:".agent/skills/lovrabet/SKILL.md"}]},antigravity:{name:"Antigravity",description:"Antigravity IDE",folders:[".agent"],files:[{type:"file",path:".agent/skills/lovrabet/SKILL.md"}]}};export const CORE_IDE_LIST=["claude","cline","codebuddy","codex","cursor","opencode","qoder","trae","windsurf"];export const IDE_LIST=["antigravity","claude","cline","codebuddy","codex","cursor","opencode","qoder","trae","windsurf","agent"]
|
|
3
|
+
;export const ALL_CORE_IDES=["cursor","windsurf","claude","cline","codex","opencode","qoder","codebuddy","trae"];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{createJqFilter,resolveBundledJqPaths}from"@lovrabet/cli-framework";import{CliErrors}from"../errors.js";export const applyJqFilter=createJqFilter(CliErrors,{bundledJqPaths:resolveBundledJqPaths()});
|
package/lib/utils/cdn-config.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{getTemplateBaseUrl}from"../utils/config.js";export async function fetchCdnConfig(){const baseUrl=getTemplateBaseUrl();const candidates=[`${baseUrl}/config.json`,`${baseUrl}/config/index.json`];for(const cdnUrl of candidates){try{const response=await fetch(cdnUrl,{headers:{Accept:"application/json"}});if(!response.ok){continue}const data=await response.json();if(!data.cli?.stableVersion||!data.sdk?.node?.stableVersion){continue}return data}catch{}}return null}let cachedConfig=null;let cacheTime=0;const CACHE_TTL=5*60*1e3;const FAILURE_CACHE_TTL=60*1e3;let hasCachedConfig=false;export async function getCdnConfig(){const now=Date.now();if(hasCachedConfig){const ttl=cachedConfig?CACHE_TTL:FAILURE_CACHE_TTL;if(now-cacheTime<ttl){return cachedConfig}}const config=await fetchCdnConfig();cachedConfig=config;cacheTime=now;hasCachedConfig=true;return config}export function clearCdnConfigCache(){cachedConfig=null;cacheTime=0;hasCachedConfig=false}
|
|
@@ -1 +1,5 @@
|
|
|
1
|
-
|
|
1
|
+
import fs from"node:fs";import path from"node:path";import semver from"semver";import{getCdnConfig}from"../utils/cdn-config.js";const FALLBACK_MIN_SDK_VERSION="1.2.0";function isNonNumericVersion(version){const nonNumericPatterns=[/^latest$/i,/^beta$/i,/^alpha$/i,/^canary$/i,/^\*$/,/^x$/];return nonNumericPatterns.some(pattern=>pattern.test(version))}function getInstalledVersion(projectPath,packageName){try{const packagePath=path.join(projectPath,"node_modules",packageName,"package.json");if(fs.existsSync(packagePath)){const pkg=JSON.parse(fs.readFileSync(packagePath,"utf-8"));return pkg.version||null}}catch{}return null}async function getSdkStableVersion(){try{const cdnConfig=await getCdnConfig();return cdnConfig?.sdk?.node?.stableVersion||null}catch{return null}}async function getSdkPackageName(){try{const cdnConfig=await getCdnConfig();return cdnConfig?.sdk?.node?.packageName||"@lovrabet/sdk"}catch{return"@lovrabet/sdk"}}export async function checkSdkVersion(projectPath){
|
|
2
|
+
const packageJsonPath=path.join(projectPath,"package.json");const[stableVersion,packageName]=await Promise.all([getSdkStableVersion(),getSdkPackageName()]);const minVersion=stableVersion||FALLBACK_MIN_SDK_VERSION;if(!fs.existsSync(packageJsonPath)){return{installed:false,version:null,needsUpgrade:false,minVersion:minVersion,packageName:packageName,stableVersion:stableVersion}}try{const packageJson=JSON.parse(fs.readFileSync(packageJsonPath,"utf8"));const dependencies=packageJson.dependencies||{};const devDependencies=packageJson.devDependencies||{};const declaredVersion=dependencies[packageName]||devDependencies[packageName];if(!declaredVersion){return{installed:false,version:null,needsUpgrade:false,minVersion:minVersion,packageName:packageName,stableVersion:stableVersion}}let actualVersion=getInstalledVersion(projectPath,packageName);if(!actualVersion){actualVersion=declaredVersion}if(isNonNumericVersion(declaredVersion)){return{installed:true,version:actualVersion,needsUpgrade:false,
|
|
3
|
+
minVersion:minVersion,packageName:packageName,stableVersion:stableVersion}}const coercedVersion=semver.coerce(actualVersion);const coercedStable=semver.coerce(minVersion);const needsUpgrade=coercedVersion&&coercedStable?semver.lt(coercedVersion,coercedStable):false;return{installed:true,version:actualVersion,needsUpgrade:needsUpgrade,minVersion:minVersion,packageName:packageName,stableVersion:stableVersion}}catch{return{installed:false,version:null,needsUpgrade:false,minVersion:minVersion,packageName:packageName,stableVersion:stableVersion}}}export function checkSdkVersionSync(projectPath){const packageJsonPath=path.join(projectPath,"package.json");const packageName="@lovrabet/sdk";if(!fs.existsSync(packageJsonPath)){return{installed:false,version:null,needsUpgrade:false,minVersion:FALLBACK_MIN_SDK_VERSION,packageName:packageName,stableVersion:null}}try{const packageJson=JSON.parse(fs.readFileSync(packageJsonPath,"utf8"));const dependencies=packageJson.dependencies||{}
|
|
4
|
+
;const devDependencies=packageJson.devDependencies||{};const declaredVersion=dependencies[packageName]||devDependencies[packageName];if(!declaredVersion){return{installed:false,version:null,needsUpgrade:false,minVersion:FALLBACK_MIN_SDK_VERSION,packageName:packageName,stableVersion:null}}let actualVersion=getInstalledVersion(projectPath,packageName);if(!actualVersion){actualVersion=declaredVersion}if(isNonNumericVersion(declaredVersion)){return{installed:true,version:actualVersion,needsUpgrade:false,minVersion:FALLBACK_MIN_SDK_VERSION,packageName:packageName,stableVersion:null}}const coercedVersion=semver.coerce(actualVersion);const needsUpgrade=coercedVersion?semver.lt(coercedVersion,FALLBACK_MIN_SDK_VERSION):false;return{installed:true,version:actualVersion,needsUpgrade:needsUpgrade,minVersion:FALLBACK_MIN_SDK_VERSION,packageName:packageName,stableVersion:null}}catch{return{installed:false,version:null,needsUpgrade:false,minVersion:FALLBACK_MIN_SDK_VERSION,packageName:packageName,
|
|
5
|
+
stableVersion:null}}}export function printSdkUpgradeWarning(result){if(!result.needsUpgrade)return;const yellow="[33m";const reset="[0m";const bold="[1m";const packageName=result.packageName||"@lovrabet/sdk";const stableVersion=result.stableVersion||result.minVersion;const upgradeCommand=`npm install ${packageName}@${stableVersion||"latest"}`;console.log();console.log(`${yellow}${bold}↪ SDK update available${reset}`);console.log(`${yellow} Current version: ${packageName}@${result.version}${reset}`);console.log(`${yellow} Stable version: ${stableVersion}${reset}`);console.log(`${yellow} Upgrade command: ${upgradeCommand}${reset}`);console.log()}
|
|
@@ -1 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
import{readFileSync}from"node:fs";import{resolve,dirname}from"node:path";import{fileURLToPath}from"node:url";import semver from"semver";import{getCliVersionPolicy}from"../utils/cli-version-policy.js";import{NPM_PACKAGE_NAME}from"../constant/cli.js";import{CliErrors}from"../errors.js";export function getCliUpgradeCommand(result){const targetVersion=result.stableVersion||"latest";return`npm install -g ${NPM_PACKAGE_NAME}@${targetVersion}`}function getCurrentCliVersion(){try{const currentFilePath=fileURLToPath(import.meta.url);const cliRootDir=resolve(dirname(currentFilePath),"../..");const cliPackageJsonPath=resolve(cliRootDir,"package.json");const packageJson=JSON.parse(readFileSync(cliPackageJsonPath,"utf-8"));return packageJson.version||"1.0.0"}catch{return"1.0.0"}}export async function checkCliVersion(){const currentVersion=getCurrentCliVersion();const policy=await getCliVersionPolicy();const stableVersion=policy?.stableVersion||null;const minimumVersion=policy?.minimumVersion||null
|
|
2
|
+
;let needsUpgrade=false;let belowMinimum=false;const current=semver.coerce(currentVersion);if(current&&stableVersion){try{const stable=semver.coerce(stableVersion);if(stable)needsUpgrade=semver.lt(current,stable)}catch{}}if(current&&minimumVersion){try{const minimum=semver.coerce(minimumVersion);if(minimum)belowMinimum=semver.lt(current,minimum)}catch{}}if(belowMinimum){needsUpgrade=true}return{currentVersion:currentVersion,stableVersion:stableVersion,minimumVersion:minimumVersion,needsUpgrade:needsUpgrade,belowMinimum:belowMinimum,isPreRelease:false,upgradeMessage:policy?.upgradeMessage,minimumVersionMessage:policy?.minimumVersionMessage}}export function printCliUpgradeWarning(result){if(!result.needsUpgrade&&!result.belowMinimum)return;const red="[31m";const yellow="[33m";const reset="[0m";const bold="[1m";const upgradeCommand=getCliUpgradeCommand(result);console.log();if(result.belowMinimum){console.log(`${red}${bold}↪ Critical CLI upgrade required${reset}`)
|
|
3
|
+
;console.log(`${red} Current CLI version: ${result.currentVersion}${reset}`);if(result.minimumVersion){console.log(`${red} Minimum supported: ${result.minimumVersion}${reset}`)}if(result.stableVersion&&result.stableVersion!==result.minimumVersion){console.log(`${red} Recommended stable: ${result.stableVersion}${reset}`)}if(result.minimumVersionMessage){console.log(`${red} ${result.minimumVersionMessage}${reset}`)}console.log(`${red} Upgrade command: ${upgradeCommand}${reset}`)}else{console.log(`${yellow}${bold}↪ New version available${reset}`);console.log(`${yellow} Current CLI version: ${result.currentVersion}${reset}`);console.log(`${yellow} Stable version: ${result.stableVersion}${reset}`);if(result.upgradeMessage){console.log(`${yellow} ${result.upgradeMessage}${reset}`)}console.log(`${yellow} Upgrade command: ${upgradeCommand}${reset}`)}console.log()}export function assertCliVersionSupported(result){if(!result.belowMinimum)return
|
|
4
|
+
;const detail=[result.minimumVersionMessage,`Current version: ${result.currentVersion}`,result.minimumVersion?`Minimum supported: ${result.minimumVersion}`:null,`Upgrade command: ${getCliUpgradeCommand(result)}`].filter(Boolean).join("\n");throw CliErrors.validation("Current CLI version is below the service compatibility support line.",detail)}
|
|
@@ -1 +1,3 @@
|
|
|
1
|
-
|
|
1
|
+
import{getCliVersionPolicyUrl,getProjectTemplateAssetBaseUrl,getProjectTemplateLegacyAssetBaseUrl}from"../constant/cdn.js";import semver from"semver";const CACHE_TTL=5*60*1e3;const FAILURE_CACHE_TTL=60*1e3;const FETCH_TIMEOUT_MS=3e3;export function isBetaCliVersion(version){const parsed=semver.valid(version);return parsed?semver.prerelease(parsed)?.[0]==="beta":false}export function resolveProjectTemplateDescriptor(config,cliVersion){if(isBetaCliVersion(cliVersion)){return config.beta?.projectTemplate??config.projectTemplate}return config.projectTemplate}function pickString(value){return typeof value==="string"&&value.trim().length>0?value.trim():null}function normalizeCliVersionPolicy(raw){if(!raw||typeof raw!=="object")return null;const source=raw;const cliSource=source.cli&&typeof source.cli==="object"?source.cli:source;const stableVersion=pickString(cliSource.stableVersion)||pickString(cliSource.latestVersion)||pickString(cliSource.recommendedVersion)
|
|
2
|
+
;const minimumVersion=pickString(cliSource.minimumVersion)||pickString(cliSource.minVersion);if(!stableVersion&&!minimumVersion)return null;return{stableVersion:stableVersion,minimumVersion:minimumVersion,upgradeMessage:pickString(cliSource.upgradeMessage)||undefined,minimumVersionMessage:pickString(cliSource.minimumVersionMessage)||undefined}}async function fetchRabetbaseCdnConfigAt(url){const controller=new AbortController;const timeoutId=setTimeout(()=>controller.abort(),FETCH_TIMEOUT_MS);try{const response=await fetch(url,{headers:{Accept:"application/json"},signal:controller.signal});if(!response.ok)return null;const parsed=await response.json();return parsed&&typeof parsed==="object"?parsed:null}catch{return null}finally{clearTimeout(timeoutId)}}export async function fetchRabetbaseCdnConfig(){return fetchRabetbaseCdnConfigAt(getCliVersionPolicyUrl())}export async function fetchProjectTemplateCdnConfig(){const config=await getRabetbaseCdnConfig();return config?{config:config,
|
|
3
|
+
assetBaseUrl:getProjectTemplateAssetBaseUrl(),legacyAssetBaseUrl:getProjectTemplateLegacyAssetBaseUrl()}:null}export async function fetchCliVersionPolicy(){return normalizeCliVersionPolicy(await fetchRabetbaseCdnConfig())}let cachedConfig=null;let cacheTime=0;let hasCachedConfig=false;export async function getRabetbaseCdnConfig(){const now=Date.now();if(hasCachedConfig){const ttl=cachedConfig?CACHE_TTL:FAILURE_CACHE_TTL;if(now-cacheTime<ttl)return cachedConfig}cachedConfig=await fetchRabetbaseCdnConfig();cacheTime=now;hasCachedConfig=true;return cachedConfig}export async function getCliVersionPolicy(){return normalizeCliVersionPolicy(await getRabetbaseCdnConfig())}export function clearCliVersionPolicyCache(){cachedConfig=null;cacheTime=0;hasCachedConfig=false}
|
package/lib/utils/config.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{initEnv}from"../constant/env.js";import{readRawConfig,getConfigAppCode as getConfigAppCodeFromContext,getMultiAppConfigs as getMultiAppConfigsFromContext,getTemplateBaseUrl as getTemplateBaseUrlFromContext}from"../context.js";export{getProjectConfigPath,getGlobalConfigPath}from"../context.js";export{isInProject}from"../context.js";export function readConfig(projectRoot){const config=readRawConfig(projectRoot);if(config.env&&typeof config.env==="string"){initEnv(config.env)}return config}export function getConfigAppCode(){return getConfigAppCodeFromContext()}export function getMultiAppConfigs(scope="project"){return getMultiAppConfigsFromContext(scope)}export function getTemplateBaseUrl(){return getTemplateBaseUrlFromContext()}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
function toFiniteNumber(value){if(typeof value==="number"&&Number.isFinite(value)){return value}if(typeof value==="string"){const text=value.trim();if(!text)return undefined;const parsed=Number(text);if(Number.isFinite(parsed))return parsed}return undefined}export function normalizeEntityWithIdResponse(raw){const primitiveId=toFiniteNumber(raw);if(primitiveId!==undefined){return{id:primitiveId,entity:{id:primitiveId}}}if(!raw||typeof raw!=="object"){return{id:undefined,entity:{}}}const entity={...raw};const id=toFiniteNumber(entity.id);if(id!==undefined){entity.id=id}return{id:id,entity:entity}}
|
package/lib/utils/file-utils.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{existsSync,mkdirSync,copyFileSync,readdirSync,statSync}from"node:fs";import{join}from"node:path";export async function copyDir(src,dest){const stat=statSync(src);if(stat.isDirectory()){if(!existsSync(dest)){mkdirSync(dest,{recursive:true})}const files=readdirSync(src);for(const file of files){await copyDir(join(src,file),join(dest,file))}}else{copyFileSync(src,dest)}}export function ensureDir(dir){if(!existsSync(dir)){mkdirSync(dir,{recursive:true})}}export function pathExists(path){return existsSync(path)}
|
package/lib/utils/guides-cdn.js
CHANGED
|
@@ -1 +1,3 @@
|
|
|
1
|
-
|
|
1
|
+
import{mkdirSync,writeFileSync}from"node:fs";import{dirname,join}from"node:path";import{homedir}from"node:os";import{getTemplateBaseUrl}from"../utils/config.js";function getGuidesCdnUrl(){const baseUrl=getTemplateBaseUrl();return`${baseUrl}/skills/guides.json`}const CACHE_DIR=join(homedir(),".lovrabet","cache");export async function fetchGuidesFromCDN(){const cdnUrl=getGuidesCdnUrl();const response=await fetch(cdnUrl,{headers:{Accept:"application/json"}});if(!response.ok){throw new Error(`CDN request failed: ${response.status} ${response.statusText}`)}const data=await response.json();if(!data.guides||typeof data.guides!=="object"){throw new Error("CDN returned invalid data")}return data}export function writeGuidesToProject(guidesData,projectRoot,basePath=".lovrabet/skill/guides",_providedFlags){const guidesDestDir=join(projectRoot,basePath);mkdirSync(guidesDestDir,{recursive:true});for(const[key,guide]of Object.entries(guidesData.guides)){let content=guide.content
|
|
2
|
+
;if(guide.lastUpdated){content=appendUpdateTime(content,guide.lastUpdated)}writeFileSync(join(guidesDestDir,`${key}.md`),content,"utf-8")}}export function appendUpdateTime(content,lastUpdated){content=content.replace(/\n*>更新时间:.*$/m,"");return content.trimEnd()+`\n\n>更新时间:${lastUpdated}`}export function getSkillTemplate(guidesData){return guidesData.skillTemplate?.content||""}export function appendExtendContents(content,guidesData,_providedFlags){const extendSections=[];for(const[,guide]of Object.entries(guidesData.guides)){if(guide.extendContent){extendSections.push(guide.extendContent.trimEnd())}}if(extendSections.length===0){return content}return content.trimEnd()+"\n\n"+extendSections.join("\n\n")+"\n"}export function writeSkillFile(guidesData,destPath,ideDisplayName){const template=getSkillTemplate(guidesData);if(!template){throw new Error("CDN data is missing skillTemplate")}const destDir=dirname(destPath);mkdirSync(destDir,{recursive:true})
|
|
3
|
+
;let content=template.replace(/\{\{IDE_NAME\}\}/g,ideDisplayName);content=appendExtendContents(content,guidesData);if(guidesData.skillTemplate.lastUpdated){content=appendUpdateTime(content,guidesData.skillTemplate.lastUpdated)}writeFileSync(destPath,content,"utf-8")}export async function installGuides(projectRoot){const guidesData=await fetchGuidesFromCDN();writeGuidesToProject(guidesData,projectRoot);return Object.keys(guidesData.guides).length}export function getGuidesSummary(guidesData){return Object.entries(guidesData.guides).map(([key,guide])=>({key:key,title:guide.title,path:guide.path}))}
|
package/lib/utils/http-client.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
export async function httpRequest(url,options={}){const{timeout:timeout=3e4,retries:retries=3,retryDelay:retryDelay=1e3,headers:headers={}}=options;let lastError=null;for(let attempt=0;attempt<=retries;attempt++){try{const controller=new AbortController;const timeoutId=setTimeout(()=>controller.abort(),timeout);const response=await fetch(url,{headers:headers,signal:controller.signal});clearTimeout(timeoutId);let data;const contentType=response.headers.get("content-type");if(contentType?.includes("application/json")){data=await response.json()}else{data=await response.text()}return{ok:response.ok,status:response.status,statusText:response.statusText,data:data,headers:response.headers,url:response.url,text:()=>response.text()}}catch(error){lastError=error instanceof Error?error:new Error(String(error));if(attempt===retries){break}if(shouldRetry(error)){console.log(`* Request failed; retry ${attempt+1} in ${retryDelay}ms...`);await sleep(retryDelay);continue}else{break}}}
|
|
2
|
+
throw lastError||new Error("Request failed")}function shouldRetry(error){if(error instanceof Error){if(error.name==="AbortError")return false;if(error.name==="TypeError"&&error.message.includes("fetch"))return true;if(error.message.includes("ECONNRESET"))return true;if(error.message.includes("ENOTFOUND"))return false}return false}function sleep(ms){return new Promise(resolve=>setTimeout(resolve,ms))}export function validateUrl(url){try{new URL(url);return true}catch{return false}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
function env(name){return process.env[`RABETBASE_${name}`]||process.env[`LOVRABET_${name}`]||undefined}export function isNonInteractive(flags){return!!(flags.nonInteractive||flags.ci||env("CI")==="true"||process.env.CI==="true"||!process.stdout.isTTY||!isStdinRawModeSupported())}function isStdinRawModeSupported(){if(!process.stdin.isTTY)return false;try{const wasRaw=process.stdin.isRaw;process.stdin.setRawMode(true);process.stdin.setRawMode(wasRaw??false);return true}catch{return false}}
|
package/lib/utils/logger.js
CHANGED
|
@@ -1 +1,3 @@
|
|
|
1
|
-
|
|
1
|
+
import winston from"winston";import fs from"node:fs";import path from"node:path";class Logger{winstonLogger;logFilePath;currentRawCommand="";constructor(){this.logFilePath=""}setRawCommand(rawCommand){this.currentRawCommand=rawCommand}initWinstonLogger(){const dir=path.dirname(this.logFilePath);if(!fs.existsSync(dir)){fs.mkdirSync(dir,{recursive:true})}const customFormat=winston.format.combine(winston.format.timestamp(),winston.format.errors({stack:true}),winston.format.printf(info=>{const logEntry={timestamp:info.timestamp||(new Date).toISOString(),level:info.level||"info",command:info.command||"unknown",rawCommand:info.rawCommand||this.currentRawCommand||undefined,message:info.message||"",duration:info.duration||undefined,details:info.details||undefined};return JSON.stringify(logEntry)}));this.winstonLogger=winston.createLogger({level:"info",format:customFormat,transports:[new winston.transports.File({filename:this.logFilePath,level:"info"})],silent:false});winston.addColors({
|
|
2
|
+
success:"green",error:"red",warn:"yellow",info:"blue"})}setLogPath(projectPath){this.logFilePath=path.join(projectPath,".lovrabet.log");if(this.winstonLogger){this.winstonLogger.clear()}this.initWinstonLogger()}info(command,message,details){if(!this.logFilePath||!this.winstonLogger)return;this.winstonLogger.info(message,{command:command,details:details})}success(command,message,duration,details){if(!this.logFilePath||!this.winstonLogger)return;this.winstonLogger.log("info",message,{level:"success",command:command,duration:duration,details:details})}error(command,message,details){if(!this.logFilePath||!this.winstonLogger)return;this.winstonLogger.error(message,{command:command,details:details})}warn(command,message,details){if(!this.logFilePath||!this.winstonLogger)return;this.winstonLogger.warn(message,{command:command,details:details})}async logTask(command,taskName,task){const startTime=Date.now();this.info(command,`Starting: ${taskName}`);try{const result=await task()
|
|
3
|
+
;const duration=Date.now()-startTime;this.success(command,`Completed: ${taskName}`,duration);return result}catch(error){const duration=Date.now()-startTime;this.error(command,`Failed: ${taskName}`,{error:error instanceof Error?error.message:String(error),duration:duration});throw error}}readLogs(){try{if(!fs.existsSync(this.logFilePath)){return[]}const content=fs.readFileSync(this.logFilePath,"utf8");return content.split("\n").filter(line=>line.trim()).map(line=>JSON.parse(line))}catch(error){console.warn("Failed to read logs:",error);return[]}}clearLogs(){try{if(fs.existsSync(this.logFilePath)){fs.writeFileSync(this.logFilePath,"","utf8")}}catch(error){console.warn("Failed to clear logs:",error)}}getWinstonInstance(){return this.winstonLogger}}export const logger=new Logger;
|
package/lib/utils/params.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{CliErrors}from"../errors.js";export function parseJsonParams(paramsStr){if(!paramsStr)return undefined;let parsed;try{parsed=JSON.parse(paramsStr)}catch{throw CliErrors.validation(`Invalid JSON for --params: ${paramsStr}`)}if(!parsed||typeof parsed!=="object"||Array.isArray(parsed)){throw CliErrors.validation("--params must be a JSON object",`Example: --params '{"id":123}'`)}return parsed}
|
package/lib/utils/platform.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export const isWindows=process.platform==="win32";export function resolveNpmBin(cmd){return isWindows?`${cmd}.cmd`:cmd}
|
package/lib/utils/sleep.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export function sleep(
|
|
1
|
+
export function sleep(ms){return new Promise(resolve=>setTimeout(resolve,ms))}
|
|
@@ -1 +1,5 @@
|
|
|
1
|
-
|
|
1
|
+
import fs from"node:fs";import path from"node:path";import{logger}from"../utils/logger.js";import{getCliVersion}from"../utils/version.js";const CLI_VERSION=getCliVersion();export class TemplateReplacer{static pad(value){return String(value).padStart(2,"0")}static formatLocalTimestamp(date){const year=date.getFullYear();const month=this.pad(date.getMonth()+1);const day=this.pad(date.getDate());const hour=this.pad(date.getHours());const minute=this.pad(date.getMinutes());const second=this.pad(date.getSeconds());return{createdAt:`${year}-${month}-${day} ${hour}:${minute}:${second}`,createdDate:`${year}-${month}-${day}`,createdTime:`${hour}:${minute}:${second}`}}static toComponentName(pageName){const lastSegment=pageName.split("/").pop()||pageName;return lastSegment.split("-").map(word=>word.charAt(0).toUpperCase()+word.slice(1).toLowerCase()).join("")}static toDisplayTitle(pageName){const lastSegment=pageName.split("/").pop()||pageName
|
|
2
|
+
;return lastSegment.split("-").map(word=>word.charAt(0).toUpperCase()+word.slice(1).toLowerCase()).join(" ")}static replaceContent(content,pageName,templateName){const componentName=this.toComponentName(pageName);const displayTitle=this.toDisplayTitle(pageName);const{createdAt:createdAt,createdDate:createdDate,createdTime:createdTime}=this.formatLocalTimestamp(new Date);let replacedContent=content.replace(/\{CliVersion\}/g,CLI_VERSION).replace(/\{ComponentName\}/g,componentName).replace(/\{DisplayTitle\}/g,displayTitle).replace(/\{PageName\}/g,pageName).replace(/\{TemplateName\}/g,templateName).replace(/\{CreatedAt\}/g,createdAt).replace(/\{CreatedDate\}/g,createdDate).replace(/\{CreatedTime\}/g,createdTime);return replacedContent}static replaceApiContent(content,appCode,modelConfigs,exampleModelName,apiFileName,configName,clientConfigParam,varPrefix,sdkConfigFileName){const now=new Date;const createdAt=now.toISOString();const formattedModelConfigs=modelConfigs.map(config=>{
|
|
3
|
+
const parts=[`datasetCode: "${config.datasetCode}"`,`tableName: "${config.tableName}"`,`name: "${config.name}"`];if(config.alias){parts.push(`alias: "${config.alias}"`)}return`\n { ${parts.join(", ")} },`}).join("");const firstModelName=exampleModelName||modelConfigs[0]?.alias||"YourModel";let replacedContent=content.replace(/\{AppCode\}/g,appCode).replace(/\{ModelConfigs\}/g,formattedModelConfigs).replace(/\{ExampleModelName\}/g,firstModelName).replace(/\{ApiFileName\}/g,apiFileName||"api").replace(/\{ConfigName\}/g,configName||"default").replace(/\{ClientConfigParam\}/g,clientConfigParam||"").replace(/\{SdkConfigFileName\}/g,sdkConfigFileName||"sdk-config").replace(/\{VarPrefix\}/g,varPrefix||"LOVRABET").replace(/\{CreatedAt\}/g,createdAt);return replacedContent}static async processTemplate(templatePath,targetPath,pageName,templateName,enableLogging=true){const startTime=Date.now();try{if(enableLogging){logger.info("template","Starting template content replacement",{
|
|
4
|
+
templatePath:templatePath,targetPath:targetPath,pageName:pageName,templateName:templateName})}await fs.promises.mkdir(targetPath,{recursive:true});await this.processDirectory(templatePath,targetPath,pageName,templateName);if(enableLogging){const duration=Date.now()-startTime;logger.success("template","Template content replacement completed",duration,{pageName:pageName,templateName:templateName})}}catch(error){if(enableLogging){const duration=Date.now()-startTime;logger.error("template","Template content replacement failed",{templatePath:templatePath,targetPath:targetPath,pageName:pageName,templateName:templateName,error:error instanceof Error?error.message:String(error),duration:duration})}throw error}}static async processDirectory(sourceDir,targetDir,pageName,templateName){const entries=await fs.promises.readdir(sourceDir,{withFileTypes:true});for(const entry of entries){const sourcePath=path.join(sourceDir,entry.name);let targetPath=path.join(targetDir,entry.name)
|
|
5
|
+
;if(entry.name.endsWith(".tpl")){targetPath=path.join(targetDir,entry.name.replace(/\.tpl$/,""))}if(entry.isDirectory()){await fs.promises.mkdir(targetPath,{recursive:true});await this.processDirectory(sourcePath,targetPath,pageName,templateName)}else if(entry.isFile()){await this.processFile(sourcePath,targetPath,pageName,templateName)}}}static async processFile(sourcePath,targetPath,pageName,templateName){const fileExtension=path.extname(sourcePath).toLowerCase();if(sourcePath.endsWith(".tpl")){targetPath=targetPath.replace(/\.tpl$/,"")}const textFileExtensions=[".tsx",".ts",".jsx",".js",".json",".md",".css",".scss",".tpl"];if(textFileExtensions.includes(fileExtension)||sourcePath.endsWith(".tpl")){const content=await fs.promises.readFile(sourcePath,"utf8");const replacedContent=this.replaceContent(content,pageName,templateName);await fs.promises.writeFile(targetPath,replacedContent,"utf8")}else{await fs.promises.copyFile(sourcePath,targetPath)}}}
|
|
@@ -1 +1,3 @@
|
|
|
1
|
-
|
|
1
|
+
import{mkdir,readFile,writeFile}from"node:fs/promises";import{homedir}from"node:os";import{dirname,join}from"node:path";import semver from"semver";import{CLI_BIN_NAME,NPM_PACKAGE_NAME}from"../constant/cli.js";import{getCliVersionPolicy}from"../utils/cli-version-policy.js";import{getCliVersion}from"../utils/version.js";const UPDATE_CHECK_TTL_MS=12*60*60*1e3;const UPDATE_NOTICE_TTL_MS=24*60*60*1e3;function isUpdateNoticeDisabled(){const raw=process.env.RABETBASE_NO_UPDATE_NOTICE?.trim().toLowerCase();return raw==="1"||raw==="true"||raw==="yes"}function cacheRoot(){return process.env.XDG_CACHE_HOME||process.env.LOCALAPPDATA||join(homedir(),".cache")}export function getUpdateNoticeCachePath(){return join(cacheRoot(),"rabetbase-cli","update-check.json")}async function readUpdateNoticeCache(){try{const content=await readFile(getUpdateNoticeCachePath(),"utf8");const parsed=JSON.parse(content);if(!parsed||typeof parsed!=="object")return{};return parsed}catch{return{}}}
|
|
2
|
+
async function writeUpdateNoticeCache(cache){try{const file=getUpdateNoticeCachePath();await mkdir(dirname(file),{recursive:true});await writeFile(file,`${JSON.stringify(cache,null,2)}\n`,"utf8")}catch{}}function isFreshCheck(cache,now){return typeof cache.checkedAt==="number"&&now-cache.checkedAt<UPDATE_CHECK_TTL_MS}function isRecentlyNotified(cache,latest,now){return cache.lastNotifiedVersion===latest&&typeof cache.lastNotifiedAt==="number"&&now-cache.lastNotifiedAt<UPDATE_NOTICE_TTL_MS}export function buildNpmVersionUrl(version){return`https://www.npmjs.com/package/${NPM_PACKAGE_NAME}/v/${version}`}export async function resolveLatestUpdateNotice(){if(isUpdateNoticeDisabled())return null;try{const now=Date.now();const current=getCliVersion();const cache=await readUpdateNoticeCache();let latest=isFreshCheck(cache,now)?cache.latest?.trim():undefined;if(!latest&&!isFreshCheck(cache,now)){const policy=await getCliVersionPolicy();latest=policy?.stableVersion?.trim()||undefined
|
|
3
|
+
;await writeUpdateNoticeCache({...cache,checkedAt:now,latest:latest,failed:!latest})}if(!latest||!semver.valid(current)||!semver.valid(latest))return null;if(semver.gte(current,latest))return null;if(isRecentlyNotified(cache,latest,now))return null;const command=`${CLI_BIN_NAME} update`;await writeUpdateNoticeCache({...cache,checkedAt:isFreshCheck(cache,now)?cache.checkedAt:now,latest:latest,failed:false,lastNotifiedVersion:latest,lastNotifiedAt:now});return{command:command,current:current,latest:latest,url:buildNpmVersionUrl(latest),message:`${CLI_BIN_NAME} ${latest} available, current ${current}, run: ${command}`}}catch{return null}}
|