@happyvertical/smrt-cli 0.55.9 → 0.55.11

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.
Files changed (67) hide show
  1. package/AGENTS.md +11 -19
  2. package/README.md +4 -0
  3. package/agents/cookbook-apply.md +65 -0
  4. package/agents/kitchen.md +111 -0
  5. package/agents/process-fixture-isolation.md +29 -0
  6. package/cookbooks/bakery.cookbook.json +187 -0
  7. package/cookbooks/mechanic.cookbook.json +191 -0
  8. package/cookbooks/welder.cookbook.json +177 -0
  9. package/cookbooks/yoga-studio.cookbook.json +173 -0
  10. package/dist/{AuditLogCollection-WDHL-_AF-HQQINXuT.js → AuditLogCollection-WDHL-_AF-ClQNu_VR.js} +1 -1
  11. package/dist/{OidcIdentity-BUblgQLs-B3dRU6nj.js → OidcIdentity-BUblgQLs-br8RyLkA.js} +2 -2
  12. package/dist/{OidcIdentityCollection-ClOyaHeF-C7-jxx9o.js → OidcIdentityCollection-ClOyaHeF-BpQXB3mz.js} +1 -1
  13. package/dist/{ProfileAssetCollection-CRMcjLJ--CQ4QjtjK.js → ProfileAssetCollection-CRMcjLJ--C5ytBKfF.js} +3 -3
  14. package/dist/{ProfileCollection-C4INKh7Y-C22q_JqL.js → ProfileCollection-C4INKh7Y-CfkyJilm.js} +17 -17
  15. package/dist/{ProfileLinkCollection-DFfZRsgv-BsRRI9lh.js → ProfileLinkCollection-DFfZRsgv-MQ2zhD9z.js} +2 -2
  16. package/dist/{ProfileMetadataCollection-BIYKy4Y3-C6hpFkOa.js → ProfileMetadataCollection-BIYKy4Y3-DXu5L2yx.js} +1 -1
  17. package/dist/{ProfileMetafieldCollection-Buz7gzag-BLXQjqBG.js → ProfileMetafieldCollection-Buz7gzag-C2tZc1PF.js} +1 -1
  18. package/dist/{ProfileRelationshipCollection-C4g_QLI4-DNywujKX.js → ProfileRelationshipCollection-C4g_QLI4-vTnkAIAh.js} +1 -1
  19. package/dist/{ProfileTypeCollection-B7kwi1mU-DPXH67Rh.js → ProfileTypeCollection-B7kwi1mU-KwPGcUkI.js} +2 -2
  20. package/dist/apply-BNDIdixP.js +947 -0
  21. package/dist/cli-generator.d.ts.map +1 -1
  22. package/dist/commands/cookbook/apply.d.ts +102 -0
  23. package/dist/commands/cookbook/apply.d.ts.map +1 -0
  24. package/dist/commands/cookbook/recipe-index.d.ts +108 -0
  25. package/dist/commands/cookbook/recipe-index.d.ts.map +1 -0
  26. package/dist/commands/cookbook/registry.d.ts +69 -0
  27. package/dist/commands/cookbook/registry.d.ts.map +1 -0
  28. package/dist/commands/cookbook/shared.d.ts +23 -0
  29. package/dist/commands/cookbook/shared.d.ts.map +1 -0
  30. package/dist/commands/cookbook/validate.d.ts +25 -0
  31. package/dist/commands/cookbook/validate.d.ts.map +1 -0
  32. package/dist/commands/cookbook.d.ts +6 -0
  33. package/dist/commands/cookbook.d.ts.map +1 -0
  34. package/dist/commands/index.d.ts +2 -0
  35. package/dist/commands/index.d.ts.map +1 -1
  36. package/dist/commands/kitchen/ai.d.ts +34 -0
  37. package/dist/commands/kitchen/ai.d.ts.map +1 -0
  38. package/dist/commands/kitchen/apply.d.ts +52 -0
  39. package/dist/commands/kitchen/apply.d.ts.map +1 -0
  40. package/dist/commands/kitchen/mcp/catalog.d.ts +39 -0
  41. package/dist/commands/kitchen/mcp/catalog.d.ts.map +1 -0
  42. package/dist/commands/kitchen/mcp/server.d.ts +15 -0
  43. package/dist/commands/kitchen/mcp/server.d.ts.map +1 -0
  44. package/dist/commands/kitchen/mcp/tools.d.ts +68 -0
  45. package/dist/commands/kitchen/mcp/tools.d.ts.map +1 -0
  46. package/dist/commands/kitchen/planner.d.ts +71 -0
  47. package/dist/commands/kitchen/planner.d.ts.map +1 -0
  48. package/dist/commands/kitchen/run.d.ts +40 -0
  49. package/dist/commands/kitchen/run.d.ts.map +1 -0
  50. package/dist/commands/kitchen/server.d.ts +39 -0
  51. package/dist/commands/kitchen/server.d.ts.map +1 -0
  52. package/dist/commands/kitchen.d.ts +7 -0
  53. package/dist/commands/kitchen.d.ts.map +1 -0
  54. package/dist/{commands-NBDTnB3h.js → commands-pbRVQvix.js} +759 -9
  55. package/dist/dist-BsRSQ_hE.js +4117 -0
  56. package/dist/{dist-DuVZ0o9F.js → dist-CYVIKmvy.js} +4 -4
  57. package/dist/dist-D_WqjwkC.js +21 -0
  58. package/dist/{dist-FZLsgj__.js → dist-DxkSjKQQ.js} +2 -2
  59. package/dist/dist-ffh0LeC4.js +1788 -0
  60. package/dist/index.js +44 -16
  61. package/dist/{oidcProvisioningPrimitives-DNP9EZlU-CbUV0zfC.js → oidcProvisioningPrimitives-DNP9EZlU-CBYwksp0.js} +3 -3
  62. package/dist/{resolveIdentity-CkyqvctR-qw-nqxJ3.js → resolveIdentity-CkyqvctR-B5btFsQd.js} +14 -14
  63. package/dist/server-Dp096tZj.js +898 -0
  64. package/package.json +13 -10
  65. package/dist/dist-B-kbXFDM.js +0 -4113
  66. package/dist/dist-BKuPI8_N.js +0 -1788
  67. package/dist/dist-DqmJkgkG.js +0 -21
@@ -1,1788 +0,0 @@
1
- import { a as queryGlobal, i as tenantId, o as queryWithGlobals, r as TenantScoped, u as withSystemContext } from "./dist-FZLsgj__.js";
2
- import { ObjectRegistry, SmrtCollection, SmrtHierarchical, SmrtJunction, SmrtJunctionBase, SmrtObject, SmrtPolymorphicAssociation, crossPackageRef, field, foreignKey, smrt } from "@happyvertical/smrt-core";
3
- //#region ../tags/dist/index.js
4
- var __defProp$2$1 = Object.defineProperty;
5
- var __exportAll$1 = (all, no_symbols) => {
6
- let target = {};
7
- for (var name in all) __defProp$2$1(target, name, {
8
- get: all[name],
9
- enumerable: true
10
- });
11
- if (!no_symbols) __defProp$2$1(target, Symbol.toStringTag, { value: "Module" });
12
- return target;
13
- };
14
- ObjectRegistry.registerPackageManifest(JSON.parse(`{"version":"1.0.0","timestamp":0,"packageName":"@happyvertical/smrt-tags","packageVersion":"0.55.9","objects":{"@happyvertical/smrt-tags:TagAlias":{"name":"tagalias","className":"TagAlias","qualifiedName":"@happyvertical/smrt-tags:TagAlias","collection":"tagaliases","filePath":"/home/runner/work/smrt/smrt/packages/tags/src/tag-alias.ts","packageName":"@happyvertical/smrt-tags","fields":{"created_at":{"type":"datetime","required":false},"updated_at":{"type":"datetime","required":false},"tagSlug":{"type":"text","required":false,"default":"","description":"The tag this alternative name points to.","_meta":{"description":"The tag this alternative name points to."}},"alias":{"type":"text","required":true,"default":"","description":"Another name or a translation people may use for the tag.","_meta":{"required":true,"description":"Another name or a translation people may use for the tag."}},"language":{"type":"text","required":false,"default":"","description":"The two-letter language code of the alternative name.","_meta":{"description":"The two-letter language code of the alternative name."}},"tenantId":{"type":"text","required":false,"_meta":{"sqlType":"UUID","nullable":true,"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":false,"autoPopulate":true,"nullable":true,"mode":"optional","field":"tenantId","allowSuperAdminBypass":false}}},"createdAt":{"type":"datetime","required":false}},"methods":{"getTag":{"name":"getTag","async":true,"parameters":[],"returnType":"Promise<Tag | null>","isStatic":false,"isPublic":true},"searchByAlias":{"name":"searchByAlias","async":true,"parameters":[{"name":"_alias","type":"string","optional":false},{"name":"_language","type":"string","optional":true}],"returnType":"Promise<Tag[]>","isStatic":true,"isPublic":true},"getAliasesForTag":{"name":"getAliasesForTag","async":true,"parameters":[{"name":"_tagSlug","type":"string","optional":false}],"returnType":"Promise<TagAlias[]>","isStatic":true,"isPublic":true}},"decoratorConfig":{"tableStrategy":"sti","api":{"include":["list","get","create","update","delete"]},"mcp":{"include":["list","get","create"]},"cli":{"skipApiCheck":true},"tenantScoped":{"mode":"optional"},"conflictColumns":["tenant_id","slug","context","_meta_type"]},"extends":"SmrtObject","exportName":"TagAlias","collectionExportName":"TagAliasCollection","validationRules":[{"field":"alias","rule":"required","fieldType":"text"}],"schema":{"tableName":"tag_aliases","ddl":"CREATE TABLE IF NOT EXISTS \\"tag_aliases\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"_meta_type\\" TEXT NOT NULL,\\n \\"_meta_data\\" JSON,\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tag_slug\\" TEXT DEFAULT '',\\n \\"alias\\" TEXT DEFAULT '',\\n \\"language\\" TEXT DEFAULT '',\\n \\"tenant_id\\" UUID\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"_meta_type":{"type":"TEXT","notNull":true},"_meta_data":{"type":"JSON","notNull":false},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tag_slug":{"type":"TEXT","notNull":false,"default":""},"alias":{"type":"TEXT","notNull":false,"default":""},"language":{"type":"TEXT","notNull":false,"default":""},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false}},"indexes":[{"name":"tag_aliases_slug_context_meta_type_idx","columns":["tenant_id","slug","context","_meta_type"],"unique":true,"nullsNotDistinct":true},{"name":"tag_aliases_meta_type_idx","columns":["_meta_type"]},{"name":"tag_aliases_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"95a4bc18"},"importPath":"@happyvertical/smrt-tags"},"@happyvertical/smrt-tags:TagAliasCollection":{"name":"tagaliascollection","className":"TagAliasCollection","qualifiedName":"@happyvertical/smrt-tags:TagAliasCollection","collection":"tagaliases","filePath":"/home/runner/work/smrt/smrt/packages/tags/src/tag-aliases.ts","packageName":"@happyvertical/smrt-tags","fields":{},"methods":{"addAlias":{"name":"addAlias","async":true,"parameters":[{"name":"tagSlug","type":"string","optional":false},{"name":"alias","type":"string","optional":false},{"name":"language","type":"string","optional":true},{"name":"context","type":"string","optional":true}],"returnType":"Promise<TagAlias>","isStatic":false,"isPublic":true},"searchByAlias":{"name":"searchByAlias","async":true,"parameters":[{"name":"alias","type":"string","optional":false},{"name":"language","type":"string","optional":true}],"returnType":"Promise<Tag[]>","isStatic":false,"isPublic":true},"getAliasesForTag":{"name":"getAliasesForTag","async":true,"parameters":[{"name":"tagSlug","type":"string","optional":false},{"name":"language","type":"string","optional":true}],"returnType":"Promise<TagAlias[]>","isStatic":false,"isPublic":true},"removeAlias":{"name":"removeAlias","async":true,"parameters":[{"name":"aliasId","type":"string","optional":false}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"bulkAddAliases":{"name":"bulkAddAliases","async":true,"parameters":[{"name":"tagSlug","type":"string","optional":false},{"name":"aliases","type":"Array<object>","optional":false,"memberTypes":["string"]}],"returnType":"Promise<TagAlias[]>","isStatic":false,"isPublic":true},"getAliasesByLanguage":{"name":"getAliasesByLanguage","async":true,"parameters":[{"name":"tagSlug","type":"string","optional":false}],"returnType":"Promise<Map<string, string[]>>","isStatic":false,"isPublic":true},"findMatchingAliases":{"name":"findMatchingAliases","async":true,"parameters":[{"name":"query","type":"string","optional":false},{"name":"language","type":"string","optional":true}],"returnType":"Promise<TagAlias[]>","isStatic":false,"isPublic":true},"findByTenant":{"name":"findByTenant","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<TagAlias[]>","isStatic":false,"isPublic":true},"findGlobal":{"name":"findGlobal","async":true,"parameters":[],"returnType":"Promise<TagAlias[]>","isStatic":false,"isPublic":true},"findWithGlobals":{"name":"findWithGlobals","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<TagAlias[]>","isStatic":false,"isPublic":true}},"decoratorConfig":{},"extends":"SmrtCollection","extendsTypeArg":"TagAlias","exportName":"TagAliasCollection","collectionExportName":"TagAliasCollectionCollection","schema":{"tableName":"tag_aliases","ddl":"CREATE TABLE IF NOT EXISTS \\"tag_aliases\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"_meta_type\\" TEXT NOT NULL,\\n \\"_meta_data\\" JSON,\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tag_slug\\" TEXT DEFAULT '',\\n \\"alias\\" TEXT DEFAULT '',\\n \\"language\\" TEXT DEFAULT '',\\n \\"tenant_id\\" UUID\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"_meta_type":{"type":"TEXT","notNull":true},"_meta_data":{"type":"JSON","notNull":false},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tag_slug":{"type":"TEXT","notNull":false,"default":""},"alias":{"type":"TEXT","notNull":false,"default":""},"language":{"type":"TEXT","notNull":false,"default":""},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false}},"indexes":[{"name":"tag_aliases_slug_context_meta_type_idx","columns":["tenant_id","slug","context","_meta_type"],"unique":true,"nullsNotDistinct":true},{"name":"tag_aliases_meta_type_idx","columns":["_meta_type"]},{"name":"tag_aliases_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"95a4bc18"},"importPath":"@happyvertical/smrt-tags"},"@happyvertical/smrt-tags:Tag":{"name":"tag","className":"Tag","qualifiedName":"@happyvertical/smrt-tags:Tag","collection":"tags","filePath":"/home/runner/work/smrt/smrt/packages/tags/src/tag.ts","packageName":"@happyvertical/smrt-tags","fields":{"created_at":{"type":"datetime","required":false},"updated_at":{"type":"datetime","required":false},"parentId":{"type":"foreignKey","required":false,"related":"Tag","_meta":{"nullable":true}},"name":{"type":"text","required":true,"default":"","description":"The name people see when they pick or browse tags.","_meta":{"required":true,"description":"The name people see when they pick or browse tags."}},"level":{"type":"integer","required":false,"default":0},"description":{"type":"text","required":false,"default":"","description":"A short note on what belongs under this tag.","_meta":{"description":"A short note on what belongs under this tag."}},"metadata":{"type":"text","required":false,"default":"","description":"Extra details about the tag, saved as named items.","_meta":{"description":"Extra details about the tag, saved as named items."}},"tenantId":{"type":"text","required":false,"_meta":{"sqlType":"UUID","nullable":true,"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":false,"autoPopulate":true,"nullable":true,"mode":"optional","field":"tenantId","allowSuperAdminBypass":false}}},"createdAt":{"type":"datetime","required":false},"updatedAt":{"type":"datetime","required":false}},"methods":{"getParent":{"name":"getParent","async":true,"parameters":[],"returnType":"Promise<this | null>","isStatic":false,"isPublic":true},"getChildren":{"name":"getChildren","async":true,"parameters":[],"returnType":"Promise<this[]>","isStatic":false,"isPublic":true},"getAncestors":{"name":"getAncestors","async":true,"parameters":[],"returnType":"Promise<this[]>","isStatic":false,"isPublic":true},"getDescendants":{"name":"getDescendants","async":true,"parameters":[],"returnType":"Promise<this[]>","isStatic":false,"isPublic":true},"getHierarchy":{"name":"getHierarchy","async":true,"parameters":[],"returnType":"Promise<HierarchyView<this>>","isStatic":false,"isPublic":true},"moveTo":{"name":"moveTo","async":true,"parameters":[{"name":"newParent","type":"this | string | null","optional":false,"unionBranches":[{"type":"this"},{"type":"string"},{"type":"null"}]}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"getMetadata":{"name":"getMetadata","async":false,"parameters":[],"returnType":"TagMetadata","isStatic":false,"isPublic":true},"setMetadata":{"name":"setMetadata","async":false,"parameters":[{"name":"data","type":"TagMetadata","optional":false}],"returnType":"void","isStatic":false,"isPublic":true},"updateMetadata":{"name":"updateMetadata","async":false,"parameters":[{"name":"updates","type":"Partial<TagMetadata>","optional":false}],"returnType":"void","isStatic":false,"isPublic":true},"getBySlug":{"name":"getBySlug","async":true,"parameters":[{"name":"_slug","type":"string","optional":false},{"name":"_context","type":"string","optional":true}],"returnType":"Promise<Tag | null>","isStatic":true,"isPublic":true},"getRootTags":{"name":"getRootTags","async":true,"parameters":[{"name":"_context","type":"string","optional":true,"default":"global"}],"returnType":"Promise<Tag[]>","isStatic":true,"isPublic":true}},"decoratorConfig":{"tableStrategy":"sti","api":{"include":["list","get","create","update","delete"]},"mcp":{"include":["list","get","create","update"]},"cli":{"skipApiCheck":true},"tenantScoped":{"mode":"optional"},"conflictColumns":["tenant_id","slug","context","_meta_type"]},"extends":"SmrtHierarchical","exportName":"Tag","collectionExportName":"TagCollection","displayLabelField":"name","validationRules":[{"field":"name","rule":"required","fieldType":"text"}],"schema":{"tableName":"tags","ddl":"CREATE TABLE IF NOT EXISTS \\"tags\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"_meta_type\\" TEXT NOT NULL,\\n \\"_meta_data\\" JSON,\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"parent_id\\" UUID,\\n \\"name\\" TEXT DEFAULT '',\\n \\"level\\" INTEGER DEFAULT 0,\\n \\"description\\" TEXT DEFAULT '',\\n \\"metadata\\" TEXT DEFAULT '',\\n \\"tenant_id\\" UUID\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"_meta_type":{"type":"TEXT","notNull":true},"_meta_data":{"type":"JSON","notNull":false},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"parent_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"foreignKey":{"table":"tags","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"name":{"type":"TEXT","notNull":false,"default":""},"level":{"type":"INTEGER","notNull":false,"default":0},"description":{"type":"TEXT","notNull":false,"default":""},"metadata":{"type":"TEXT","notNull":false,"default":""},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false}},"indexes":[{"name":"tags_slug_context_meta_type_idx","columns":["tenant_id","slug","context","_meta_type"],"unique":true,"nullsNotDistinct":true},{"name":"tags_meta_type_idx","columns":["_meta_type"]},{"name":"tags_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"tags_parent_id_idx","columns":["parent_id"]}],"version":"4da9de3e"},"importPath":"@happyvertical/smrt-tags"},"@happyvertical/smrt-tags:TagCollection":{"name":"tagcollection","className":"TagCollection","qualifiedName":"@happyvertical/smrt-tags:TagCollection","collection":"tags","filePath":"/home/runner/work/smrt/smrt/packages/tags/src/tags.ts","packageName":"@happyvertical/smrt-tags","fields":{},"methods":{"getOrCreate":{"name":"getOrCreate","async":true,"parameters":[{"name":"slug","type":"string","optional":false},{"name":"context","type":"string","optional":true,"default":"global"}],"returnType":"Promise<Tag>","isStatic":false,"isPublic":true},"listByContext":{"name":"listByContext","async":true,"parameters":[{"name":"context","type":"string","optional":false},{"name":"parentSlug","type":"string | null","optional":true,"unionBranches":[{"type":"string"},{"type":"null"}]}],"returnType":"Promise<Tag[]>","isStatic":false,"isPublic":true},"getRootTags":{"name":"getRootTags","async":true,"parameters":[{"name":"context","type":"string","optional":true,"default":"global"}],"returnType":"Promise<Tag[]>","isStatic":false,"isPublic":true},"getChildren":{"name":"getChildren","async":true,"parameters":[{"name":"parentSlug","type":"string","optional":false},{"name":"context","type":"string","optional":true}],"returnType":"Promise<Tag[]>","isStatic":false,"isPublic":true},"getHierarchy":{"name":"getHierarchy","async":true,"parameters":[{"name":"slug","type":"string","optional":false},{"name":"context","type":"string","optional":true}],"returnType":"Promise<TagHierarchy>","isStatic":false,"isPublic":true},"moveTag":{"name":"moveTag","async":true,"parameters":[{"name":"slug","type":"string","optional":false},{"name":"newParentSlug","type":"string | null","optional":false,"unionBranches":[{"type":"string"},{"type":"null"}]},{"name":"context","type":"string","optional":true}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"mergeTag":{"name":"mergeTag","async":true,"parameters":[{"name":"fromSlug","type":"string","optional":false},{"name":"toSlug","type":"string","optional":false},{"name":"context","type":"string","optional":true}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"cleanupUnused":{"name":"cleanupUnused","async":true,"parameters":[{"name":"context","type":"string","optional":true}],"returnType":"Promise<number>","isStatic":false,"isPublic":true},"calculateLevel":{"name":"calculateLevel","async":true,"parameters":[{"name":"parentSlug","type":"string | null","optional":false,"unionBranches":[{"type":"string"},{"type":"null"}]},{"name":"context","type":"string","optional":true}],"returnType":"Promise<number>","isStatic":false,"isPublic":true},"findByTenant":{"name":"findByTenant","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<Tag[]>","isStatic":false,"isPublic":true},"findGlobal":{"name":"findGlobal","async":true,"parameters":[],"returnType":"Promise<Tag[]>","isStatic":false,"isPublic":true},"findWithGlobals":{"name":"findWithGlobals","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<Tag[]>","isStatic":false,"isPublic":true}},"decoratorConfig":{},"extends":"SmrtCollection","extendsTypeArg":"Tag","exportName":"TagCollection","collectionExportName":"TagCollectionCollection","schema":{"tableName":"tags","ddl":"CREATE TABLE IF NOT EXISTS \\"tags\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"_meta_type\\" TEXT NOT NULL,\\n \\"_meta_data\\" JSON,\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"parent_id\\" UUID,\\n \\"name\\" TEXT DEFAULT '',\\n \\"level\\" INTEGER DEFAULT 0,\\n \\"description\\" TEXT DEFAULT '',\\n \\"metadata\\" TEXT DEFAULT '',\\n \\"tenant_id\\" UUID\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"_meta_type":{"type":"TEXT","notNull":true},"_meta_data":{"type":"JSON","notNull":false},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"parent_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"foreignKey":{"table":"tags","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"name":{"type":"TEXT","notNull":false,"default":""},"level":{"type":"INTEGER","notNull":false,"default":0},"description":{"type":"TEXT","notNull":false,"default":""},"metadata":{"type":"TEXT","notNull":false,"default":""},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false}},"indexes":[{"name":"tags_slug_context_meta_type_idx","columns":["tenant_id","slug","context","_meta_type"],"unique":true,"nullsNotDistinct":true},{"name":"tags_meta_type_idx","columns":["_meta_type"]},{"name":"tags_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"tags_parent_id_idx","columns":["parent_id"]}],"version":"4da9de3e"},"importPath":"@happyvertical/smrt-tags"}},"moduleType":"smrt","recipes":[{"id":"tags.taxonomy","className":"TaxonomyRecipe","label":"Taxonomy","summary":"Organise anything with a shared set of nested tags and alternative names.","synonyms":["tags","tagging","categories","labels","topics"],"models":["@happyvertical/smrt-tags:Tag","@happyvertical/smrt-tags:TagAlias"],"nav":[{"label":"Tags","model":"@happyvertical/smrt-tags:Tag","icon":"tag","description":"The shared set of tags, including tags inside other tags."},{"label":"Alternative names","model":"@happyvertical/smrt-tags:TagAlias","icon":"book","description":"Other names and translations that lead people to the same tag."}],"requires":[],"section":{"id":"taxonomy","label":"Taxonomy","icon":"tag","description":"The tags people use to sort and find things."},"options":{"@happyvertical/smrt-tags:Tag":{"fields":{"name":{"order":1},"parentId":{"label":"Parent tag","help":"The broader tag this one sits under. Leave it empty for a top-level tag.","order":2},"description":{"order":3},"level":{"visibility":"hidden","locked":true},"metadata":{"visibility":"advanced"}}},"@happyvertical/smrt-tags:TagAlias":{"fields":{"alias":{"label":"Alternative name","order":1},"tagSlug":{"label":"Tag","order":2},"language":{"order":3}}}},"help":{"markdown":"## Overview\\n\\nTaxonomy is a shared list of tags you can use to organise anything in your app.\\nTags can sit inside other tags, so a broad tag such as \\"Events\\" can hold\\nnarrower ones such as \\"Concerts\\" and \\"Workshops\\". A tag can also have\\nalternative names, including translations, so people find it by whichever word\\nthey know.\\n\\n## Tasks\\n\\n### Add a tag\\n\\n1. Choose the **New** button above the list of tags.\\n2. Give the tag a **{field:name}** people will recognise.\\n3. Add a **{field:description}** that says what belongs under it.\\n4. Save. The tag is now ready to use.\\n\\n### Put a tag inside another tag\\n\\n1. Open the tag from the list and choose Edit.\\n2. Pick the **{field:parentId}**, the broader tag it belongs under.\\n3. Leave it empty to make the tag a top-level tag.\\n4. Save. Moving a tag moves everything under it too.\\n\\n### Add another name for a tag\\n\\n1. Open the list of alternative names and choose **New**.\\n2. Pick the **{field:tagSlug}** the new name belongs to.\\n3. Type the **{field:alias}**, for example a common nickname or a translation.\\n4. Set the **{field:language}** if the name is in a specific language.\\n5. Save. The alternative name is now on file for that tag.\\n\\n### Keep the list tidy\\n\\nKeep one tag for each idea. If two tags mean the same thing, record the second\\nas an alternative name instead of keeping both.\\n","fieldRefs":["alias","description","language","name","parentId","tagSlug"]},"demo":{"mode":"server","reasons":["Needs a server because its package depends on @happyvertical/smrt-tenancy, which do not build for a browser (#3624)."]}}],"smrtDependencies":["@happyvertical/smrt-core","@happyvertical/smrt-tenancy"],"browser":{"status":"server-only","issues":["#3624"],"via":["@happyvertical/smrt-tenancy"]},"stampsConstructors":true}`));
15
- var __defProp$1$1 = Object.defineProperty;
16
- var __getOwnPropDesc$1$1 = Object.getOwnPropertyDescriptor;
17
- var __defNormalProp$1$1 = (obj, key, value) => key in obj ? __defProp$1$1(obj, key, {
18
- enumerable: true,
19
- configurable: true,
20
- writable: true,
21
- value
22
- }) : obj[key] = value;
23
- var __decorateClass$1$1 = (decorators, target, key, kind) => {
24
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$1$1(target, key) : target;
25
- for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
26
- if (kind && result) __defProp$1$1(target, key, result);
27
- return result;
28
- };
29
- var __publicField$1$1 = (obj, key, value) => __defNormalProp$1$1(obj, typeof key !== "symbol" ? key + "" : key, value);
30
- var Tag = class extends SmrtHierarchical {
31
- _slug = "";
32
- _context = "global";
33
- get slug() {
34
- return this._slug;
35
- }
36
- set slug(value) {
37
- this._slug = value;
38
- }
39
- get context() {
40
- return this._context;
41
- }
42
- set context(value) {
43
- this._context = value;
44
- }
45
- name = "";
46
- level = 0;
47
- description = "";
48
- metadata = "";
49
- tenantId = null;
50
- createdAt = /* @__PURE__ */ new Date();
51
- updatedAt = /* @__PURE__ */ new Date();
52
- constructor(options = {}) {
53
- super(options);
54
- if (options.name) this.name = options.name;
55
- if (options.parentId !== void 0) this.parentId = options.parentId ?? null;
56
- if (options.slug) this._slug = options.slug;
57
- if (options.context !== void 0) this._context = options.context;
58
- if (options.level !== void 0) this.level = options.level;
59
- if (options.description !== void 0) this.description = options.description;
60
- if (options.metadata !== void 0) if (typeof options.metadata === "string") this.metadata = options.metadata;
61
- else this.metadata = JSON.stringify(options.metadata);
62
- }
63
- /**
64
- * Get metadata as parsed object
65
- *
66
- * @returns Parsed metadata object or empty object if no metadata
67
- */
68
- getMetadata() {
69
- const metadataValue = String(this.metadata || "");
70
- if (!metadataValue) return {};
71
- try {
72
- return JSON.parse(metadataValue);
73
- } catch {
74
- return {};
75
- }
76
- }
77
- /**
78
- * Set metadata from object
79
- *
80
- * @param data - Metadata object to store
81
- */
82
- setMetadata(data) {
83
- this.metadata = JSON.stringify(data);
84
- }
85
- /**
86
- * Update metadata by merging with existing values
87
- *
88
- * @param updates - Partial metadata to merge
89
- */
90
- updateMetadata(updates) {
91
- const current = this.getMetadata();
92
- this.setMetadata({
93
- ...current,
94
- ...updates
95
- });
96
- }
97
- /**
98
- * Convenience method for slug-based lookup
99
- *
100
- * @param slug - The slug to search for
101
- * @param context - Optional context filter
102
- * @returns Tag instance or null if not found
103
- */
104
- static async getBySlug(_slug, _context) {
105
- return null;
106
- }
107
- /**
108
- * Get root tags (no parent) for a context
109
- *
110
- * @param context - The context to filter by
111
- * @returns Array of root tags
112
- */
113
- static async getRootTags(_context = "global") {
114
- return [];
115
- }
116
- };
117
- __publicField$1$1(Tag, "__smrtPackage__", "@happyvertical/smrt-tags");
118
- __decorateClass$1$1([field({
119
- required: true,
120
- description: "The name people see when they pick or browse tags."
121
- })], Tag.prototype, "name", 2);
122
- __decorateClass$1$1([field({ description: "A short note on what belongs under this tag." })], Tag.prototype, "description", 2);
123
- __decorateClass$1$1([field({ description: "Extra details about the tag, saved as named items." })], Tag.prototype, "metadata", 2);
124
- __decorateClass$1$1([tenantId({ nullable: true })], Tag.prototype, "tenantId", 2);
125
- Tag = __decorateClass$1$1([TenantScoped({ mode: "optional" }), smrt({
126
- tableStrategy: "sti",
127
- api: { include: [
128
- "list",
129
- "get",
130
- "create",
131
- "update",
132
- "delete"
133
- ] },
134
- mcp: { include: [
135
- "list",
136
- "get",
137
- "create",
138
- "update"
139
- ] },
140
- cli: { skipApiCheck: true }
141
- })], Tag);
142
- var __defProp$10 = Object.defineProperty;
143
- var __getOwnPropDesc$9 = Object.getOwnPropertyDescriptor;
144
- var __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$10(obj, key, {
145
- enumerable: true,
146
- configurable: true,
147
- writable: true,
148
- value
149
- }) : obj[key] = value;
150
- var __decorateClass$9 = (decorators, target, key, kind) => {
151
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$9(target, key) : target;
152
- for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
153
- if (kind && result) __defProp$10(target, key, result);
154
- return result;
155
- };
156
- var __publicField$9 = (obj, key, value) => __defNormalProp$9(obj, typeof key !== "symbol" ? key + "" : key, value);
157
- var TagAlias = class extends SmrtObject {
158
- tagSlug = "";
159
- alias = "";
160
- language = "";
161
- _context = "";
162
- get context() {
163
- return this._context;
164
- }
165
- set context(value) {
166
- this._context = value;
167
- }
168
- tenantId = null;
169
- createdAt = /* @__PURE__ */ new Date();
170
- constructor(options = {}) {
171
- super(options);
172
- if (options.tagSlug !== void 0) this.tagSlug = options.tagSlug;
173
- if (options.alias) this.alias = options.alias;
174
- if (options.language !== void 0) this.language = options.language;
175
- if (options.context !== void 0) this._context = options.context;
176
- }
177
- /**
178
- * Get the tag this alias belongs to
179
- *
180
- * @returns Tag instance or null if not found
181
- */
182
- async getTag() {
183
- const { TagCollection } = await Promise.resolve().then(() => tags_exports);
184
- return await (await TagCollection.create(this.options)).get({ slug: this.tagSlug });
185
- }
186
- /**
187
- * Search tags by alias
188
- *
189
- * @param alias - The alias to search for
190
- * @param language - Optional language filter
191
- * @returns Array of matching tags
192
- */
193
- static async searchByAlias(_alias, _language) {
194
- return [];
195
- }
196
- /**
197
- * Get all aliases for a tag
198
- *
199
- * @param tagSlug - The tag slug to get aliases for
200
- * @returns Array of TagAlias instances
201
- */
202
- static async getAliasesForTag(_tagSlug) {
203
- return [];
204
- }
205
- };
206
- __publicField$9(TagAlias, "__smrtPackage__", "@happyvertical/smrt-tags");
207
- __decorateClass$9([field({ description: "The tag this alternative name points to." })], TagAlias.prototype, "tagSlug", 2);
208
- __decorateClass$9([field({
209
- required: true,
210
- description: "Another name or a translation people may use for the tag."
211
- })], TagAlias.prototype, "alias", 2);
212
- __decorateClass$9([field({ description: "The two-letter language code of the alternative name." })], TagAlias.prototype, "language", 2);
213
- __decorateClass$9([tenantId({ nullable: true })], TagAlias.prototype, "tenantId", 2);
214
- TagAlias = __decorateClass$9([TenantScoped({ mode: "optional" }), smrt({
215
- tableStrategy: "sti",
216
- api: { include: [
217
- "list",
218
- "get",
219
- "create",
220
- "update",
221
- "delete"
222
- ] },
223
- mcp: { include: [
224
- "list",
225
- "get",
226
- "create"
227
- ] },
228
- cli: { skipApiCheck: true }
229
- })], TagAlias);
230
- var tag_aliases_exports = /* @__PURE__ */ __exportAll$1({ TagAliasCollection: () => TagAliasCollection });
231
- var TagAliasCollection = class extends SmrtCollection {
232
- static _itemClass = TagAlias;
233
- /**
234
- * Add an alias to a tag (get or create)
235
- *
236
- * @param tagSlug - The tag slug
237
- * @param alias - The alias text
238
- * @param language - Optional language code
239
- * @param context - Optional context
240
- * @returns TagAlias instance
241
- */
242
- async addAlias(tagSlug, alias, language, context) {
243
- const where = {
244
- tagSlug,
245
- alias
246
- };
247
- if (language) where.language = language;
248
- if (context) where.context = context;
249
- const existing = await this.list({
250
- where,
251
- limit: 1
252
- });
253
- if (existing.length > 0) return existing[0];
254
- return await this.create({
255
- tagSlug,
256
- alias,
257
- language,
258
- context
259
- });
260
- }
261
- /**
262
- * Search tags by alias
263
- *
264
- * @param alias - The alias to search for
265
- * @param language - Optional language filter
266
- * @returns Array of matching tags
267
- */
268
- async searchByAlias(alias, language) {
269
- const where = { alias };
270
- if (language) where.language = language;
271
- const aliases = await this.list({ where });
272
- const tagSlugs = [...new Set(aliases.map((a) => a.tagSlug))];
273
- const { TagCollection } = await Promise.resolve().then(() => tags_exports);
274
- const tagCollection = await TagCollection.create(this.options);
275
- const tags = [];
276
- for (const slug of tagSlugs) {
277
- const tag = await tagCollection.get({ slug });
278
- if (tag) tags.push(tag);
279
- }
280
- return tags;
281
- }
282
- /**
283
- * Get all aliases for a tag
284
- *
285
- * @param tagSlug - The tag slug
286
- * @param language - Optional language filter
287
- * @returns Array of TagAlias instances
288
- */
289
- async getAliasesForTag(tagSlug, language) {
290
- const where = { tagSlug };
291
- if (language) where.language = language;
292
- return await this.list({ where });
293
- }
294
- /**
295
- * Remove an alias by ID
296
- *
297
- * @param aliasId - The alias UUID
298
- */
299
- async removeAlias(aliasId) {
300
- const alias = await this.get({ id: aliasId });
301
- if (alias) await alias.delete();
302
- }
303
- /**
304
- * Bulk add aliases to a tag
305
- *
306
- * @param tagSlug - The tag slug
307
- * @param aliases - Array of alias configurations
308
- * @returns Array of created TagAlias instances
309
- */
310
- async bulkAddAliases(tagSlug, aliases) {
311
- const created = [];
312
- for (const aliasData of aliases) {
313
- const tagAlias = await this.addAlias(tagSlug, aliasData.alias, aliasData.language, aliasData.context);
314
- created.push(tagAlias);
315
- }
316
- return created;
317
- }
318
- /**
319
- * Get aliases grouped by language
320
- *
321
- * @param tagSlug - The tag slug
322
- * @returns Map of language code to array of aliases
323
- */
324
- async getAliasesByLanguage(tagSlug) {
325
- const aliases = await this.getAliasesForTag(tagSlug);
326
- const grouped = /* @__PURE__ */ new Map();
327
- for (const alias of aliases) {
328
- const lang = String(alias.language || "default");
329
- if (!grouped.has(lang)) grouped.set(lang, []);
330
- grouped.get(lang)?.push(String(alias.alias));
331
- }
332
- return grouped;
333
- }
334
- /**
335
- * Find matching aliases (case-insensitive partial match)
336
- *
337
- * Note: This is a simple implementation. For production use,
338
- * consider using full-text search or fuzzy matching.
339
- *
340
- * @param query - The search query
341
- * @param language - Optional language filter
342
- * @returns Array of matching TagAlias instances
343
- */
344
- async findMatchingAliases(query, language) {
345
- const where = {};
346
- if (language) where.language = language;
347
- const all = await this.list({ where });
348
- const queryLower = query.toLowerCase();
349
- return all.filter((alias) => String(alias.alias).toLowerCase().includes(queryLower));
350
- }
351
- /**
352
- * Find all tag aliases belonging to a specific tenant
353
- *
354
- * @param tenantId - The tenant ID to filter by
355
- * @returns Array of tag aliases for the specified tenant
356
- */
357
- async findByTenant(tenantId) {
358
- return this.list({ where: { tenantId } });
359
- }
360
- /**
361
- * Find all global (tenant-less) tag aliases.
362
- *
363
- * Routes through the shared tenant-global helper so it does not throw under
364
- * an active tenant context (an explicit `tenant_id IS NULL` filter would be
365
- * flagged as an isolation violation). (#1600)
366
- *
367
- * @returns Array of global tag aliases with null tenantId
368
- */
369
- async findGlobal() {
370
- return queryGlobal(this);
371
- }
372
- /**
373
- * Find tag aliases for a tenant including global aliases.
374
- *
375
- * Fails closed if an active tenant context requests a different tenant's
376
- * rows; the admin/system path keeps the cross-tenant capability. (#1600)
377
- *
378
- * @param tenantId - The tenant ID to filter by
379
- * @returns Array of tag aliases for the tenant plus all global aliases
380
- */
381
- async findWithGlobals(tenantId) {
382
- return queryWithGlobals(this, tenantId, "TagAlias.findWithGlobals");
383
- }
384
- };
385
- var tags_exports = /* @__PURE__ */ __exportAll$1({ TagCollection: () => TagCollection });
386
- var TagCollection = class extends SmrtCollection {
387
- static _itemClass = Tag;
388
- /**
389
- * Get or create a tag with context
390
- *
391
- * @param slug - Tag slug
392
- * @param context - Tag context (default: 'global')
393
- * @returns Tag instance
394
- */
395
- async getOrCreate(slug, context = "global") {
396
- const existing = await this.list({
397
- where: {
398
- slug,
399
- context
400
- },
401
- limit: 1
402
- });
403
- if (existing.length > 0) return existing[0];
404
- return await this.create({
405
- slug,
406
- name: slug.replace(/-/g, " ").replace(/\b\w/g, (l) => l.toUpperCase()),
407
- context,
408
- level: 0
409
- });
410
- }
411
- /**
412
- * Resolve a tag by slug, optionally scoped to a context.
413
- *
414
- * Tags are identified by `(slug, context)`. When `context` is omitted
415
- * and the slug exists in more than one context, this throws a clear
416
- * ambiguity error rather than silently picking the first matching row.
417
- * Callers that know their context should pass it; callers that work in
418
- * a single-context world can leave it off.
419
- *
420
- * @returns The matching Tag, or `null` if nothing matches.
421
- * @throws Error if `context` is omitted and the slug is ambiguous.
422
- */
423
- async resolveBySlug(slug, context) {
424
- const where = { slug };
425
- if (context !== void 0) where.context = context;
426
- const matches = await this.list({
427
- where,
428
- limit: 2
429
- });
430
- if (matches.length === 0) return null;
431
- if (matches.length > 1) throw new Error(`Tag slug '${slug}' is ambiguous: resolves to ${matches.length}+ rows across contexts. Pass an explicit \`context\` argument.`);
432
- return matches[0];
433
- }
434
- /**
435
- * List tags by context with optional parent filtering by slug.
436
- *
437
- * @param context - The context to filter by
438
- * @param parentSlug - Optional parent slug to filter children. Pass an
439
- * empty string or `null` to find root tags; pass a slug to find that
440
- * tag's immediate children. Typed as `string | null` so TypeScript
441
- * callers can pass `null` without a cast — the `null` and `''` paths
442
- * are both treated as "roots only".
443
- * @returns Array of matching tags
444
- */
445
- async listByContext(context, parentSlug) {
446
- const where = { context };
447
- if (parentSlug === "" || parentSlug === null) where.parentId = null;
448
- else if (parentSlug !== void 0) {
449
- const parent = await this.get({
450
- slug: parentSlug,
451
- context
452
- });
453
- if (!parent?.id) return [];
454
- where.parentId = parent.id;
455
- }
456
- return await this.list({ where });
457
- }
458
- /**
459
- * Get root tags (no parent) for a context
460
- *
461
- * @param context - The context to filter by (default: 'global')
462
- * @returns Array of root tags
463
- */
464
- async getRootTags(context = "global") {
465
- return await this.list({ where: {
466
- context,
467
- parentId: null
468
- } });
469
- }
470
- /**
471
- * Get immediate children of a parent tag, looked up by slug.
472
- *
473
- * @param parentSlug - The parent tag slug
474
- * @param context - Optional context for the parent lookup. When omitted,
475
- * the parent slug must be unambiguous across contexts (throws if not).
476
- * @returns Array of child tags, or `[]` if the parent slug doesn't
477
- * resolve. Children are filtered to the resolved parent's context so
478
- * cross-context children don't leak in.
479
- */
480
- async getChildren(parentSlug, context) {
481
- const parent = await this.resolveBySlug(parentSlug, context);
482
- if (!parent?.id) return [];
483
- return await this.list({ where: {
484
- parentId: parent.id,
485
- context: parent.context
486
- } });
487
- }
488
- /**
489
- * Get tag hierarchy (all ancestors and descendants)
490
- *
491
- * @param slug - The tag slug
492
- * @param context - Optional context for the slug lookup. When omitted,
493
- * the slug must be unambiguous across contexts.
494
- * @returns Object with ancestors, current tag, and descendants
495
- */
496
- async getHierarchy(slug, context) {
497
- const tag = await this.resolveBySlug(slug, context);
498
- if (!tag) throw new Error(`Tag '${slug}' not found`);
499
- const [ancestors, descendants] = await Promise.all([tag.getAncestors(), tag.getDescendants()]);
500
- return {
501
- ancestors,
502
- current: tag,
503
- descendants
504
- };
505
- }
506
- /**
507
- * Move a tag to a new parent. Slug-based API; UUIDs resolved internally.
508
- *
509
- * Cycle detection is inlined here (mirroring `SmrtHierarchical.moveTo`'s
510
- * self-loop + descendant checks) so that both `parentId` and the
511
- * denormalised `level` field can be persisted in a single `save()`.
512
- * Delegating to `moveTo` would write `parentId` first and `level` in a
513
- * second save — if the second save failed, the tag would be left with
514
- * the new parent but a stale level, breaking the depth cache.
515
- *
516
- * After the moved tag persists, descendant levels are recalculated
517
- * recursively via `updateDescendantLevels`.
518
- *
519
- * @param slug - The tag to move
520
- * @param newParentSlug - The new parent slug (null for root)
521
- * @param context - Optional context. When provided, both source and new
522
- * parent are resolved within it. When omitted, both slugs must be
523
- * unambiguous across contexts; the resolver throws otherwise.
524
- * @throws Error if either slug fails to resolve, if either slug is
525
- * ambiguous across contexts (no context provided), if source and new
526
- * parent live in different contexts, or if the move would create a
527
- * cycle.
528
- */
529
- async moveTag(slug, newParentSlug, context) {
530
- const tag = await this.resolveBySlug(slug, context);
531
- if (!tag) throw new Error(`Tag '${slug}' not found`);
532
- let newParent = null;
533
- if (newParentSlug) {
534
- newParent = await this.resolveBySlug(newParentSlug, context ?? tag.context);
535
- if (!newParent) throw new Error(`Tag '${newParentSlug}' not found`);
536
- if (newParent.context !== tag.context) throw new Error(`Cannot move Tag '${slug}' (context '${tag.context}') under '${newParentSlug}' (context '${newParent.context}') \u2014 contexts must match.`);
537
- }
538
- const newParentId = newParent?.id ?? null;
539
- if (newParentId !== null && newParentId === tag.id) throw new Error(`Cannot move Tag ${tag.id} to itself.`);
540
- if (newParentId !== null) {
541
- if ((await tag.getDescendants()).some((d) => d.id === newParentId)) throw new Error(`Cannot move Tag ${tag.id} under one of its own descendants (${newParentId}) \u2014 would create a cycle.`);
542
- }
543
- tag.parentId = newParentId;
544
- tag.level = newParent ? newParent.level + 1 : 0;
545
- await tag.save();
546
- await this.updateDescendantLevels(tag);
547
- }
548
- /**
549
- * Merge one tag into another (updates all references)
550
- *
551
- * Reparents `fromTag`'s direct children onto `toTag` and recalculates
552
- * their `level` field plus the level of every descendant — without
553
- * this, children moved from a different depth would carry stale
554
- * levels relative to their new parent. `TagAlias.tagSlug` references
555
- * are also rewritten, then `fromTag` is deleted.
556
- *
557
- * Note: Consuming packages are responsible for updating their own
558
- * join tables (e.g. `asset_tags`).
559
- *
560
- * @param fromSlug - The tag to merge from
561
- * @param toSlug - The tag to merge into
562
- * @param context - Optional context. When provided, both tags are
563
- * resolved within it. When omitted, both slugs must be unambiguous
564
- * across contexts.
565
- * @throws Error if either slug fails to resolve, if either slug is
566
- * ambiguous, or if the two tags live in different contexts.
567
- */
568
- async mergeTag(fromSlug, toSlug, context) {
569
- const fromTag = await this.resolveBySlug(fromSlug, context);
570
- const toTag = await this.resolveBySlug(toSlug, context ?? fromTag?.context);
571
- if (!fromTag) throw new Error(`Source tag '${fromSlug}' not found`);
572
- if (!toTag) throw new Error(`Target tag '${toSlug}' not found`);
573
- if (!fromTag.id) throw new Error(`Source tag '${fromSlug}' has no id`);
574
- if (!toTag.id) throw new Error(`Target tag '${toSlug}' has no id`);
575
- if (fromTag.context !== toTag.context) throw new Error(`Cannot merge '${fromSlug}' (context '${fromTag.context}') into '${toSlug}' (context '${toTag.context}') \u2014 contexts must match.`);
576
- if (fromTag.id === toTag.id) throw new Error(`Cannot merge tag '${fromSlug}' into itself.`);
577
- if ((await fromTag.getDescendants()).some((d) => d.id === toTag.id)) throw new Error(`Cannot merge '${fromSlug}' into '${toSlug}' \u2014 target is a descendant of source (would create a cycle).`);
578
- const children = await this.list({ where: { parentId: fromTag.id } });
579
- const newChildLevel = toTag.level + 1;
580
- for (const child of children) {
581
- child.parentId = toTag.id;
582
- child.level = newChildLevel;
583
- await child.save();
584
- await this.updateDescendantLevels(child);
585
- }
586
- const { TagAliasCollection } = await Promise.resolve().then(() => tag_aliases_exports);
587
- const aliasCollection = await TagAliasCollection.create(this.options);
588
- const aliasContexts = [fromTag.context];
589
- if (fromTag.context === "global") aliasContexts.push("");
590
- const aliases = await aliasCollection.list({ where: {
591
- tagSlug: fromSlug,
592
- context: aliasContexts
593
- } });
594
- for (const alias of aliases) {
595
- alias.tagSlug = toSlug;
596
- await alias.save();
597
- }
598
- await this.repointTagReferences(fromTag.id, toTag.id);
599
- await fromTag.delete();
600
- }
601
- /**
602
- * Move every reference to tag `fromId` onto `toId`. A row whose natural key
603
- * includes the tag column and that already exists for `toId` (an asset
604
- * tagged with both) is a duplicate after the merge and is removed instead.
605
- * Rows are matched by tag id, which is specific to one tenant's tag, so
606
- * this reads and writes through the adapter directly.
607
- */
608
- async repointTagReferences(fromId, toId) {
609
- const tagClass = ObjectRegistry.getClassByConstructor(Tag)?.qualifiedName ?? "Tag";
610
- const tagTable = ObjectRegistry.getTableName(tagClass);
611
- for (const reference of ObjectRegistry.getIncomingReferences(tagClass)) {
612
- if (reference.tableName === tagTable) continue;
613
- if (!await this.db.tableExists(reference.tableName)) continue;
614
- const conflictColumns = ObjectRegistry.getConflictColumns(reference.className);
615
- const keyed = conflictColumns.includes(reference.column) && !(conflictColumns.length === 1 && conflictColumns[0] === "id");
616
- const rows = await this.db.list(reference.tableName, { [reference.column]: fromId });
617
- for (const row of rows) {
618
- if (keyed) {
619
- const probe = {};
620
- for (const column of conflictColumns) probe[column] = column === reference.column ? toId : row[column];
621
- if (await this.db.get(reference.tableName, probe)) {
622
- await this.db.delete(reference.tableName, { id: row.id });
623
- continue;
624
- }
625
- }
626
- await this.db.update(reference.tableName, { id: row.id }, { [reference.column]: toId });
627
- }
628
- }
629
- }
630
- /**
631
- * Remove tags with no references (cleanup unused tags)
632
- *
633
- * Note: This requires consuming packages to provide usage information.
634
- * By default, only removes tags with no children and no aliases.
635
- *
636
- * @param context - Optional context to filter cleanup
637
- */
638
- async cleanupUnused(context) {
639
- const where = {};
640
- if (context) where.context = context;
641
- const tags = await this.list({ where });
642
- const { TagAliasCollection } = await Promise.resolve().then(() => tag_aliases_exports);
643
- const aliasCollection = await TagAliasCollection.create(this.options);
644
- let deletedCount = 0;
645
- for (const tag of tags) {
646
- if (!tag.id) continue;
647
- if ((await this.list({
648
- where: { parentId: tag.id },
649
- limit: 1
650
- })).length > 0) continue;
651
- if ((await aliasCollection.list({
652
- where: { tagSlug: tag.slug },
653
- limit: 1
654
- })).length > 0) continue;
655
- await tag.delete();
656
- deletedCount++;
657
- }
658
- return deletedCount;
659
- }
660
- /**
661
- * Calculate hierarchy level for a tag, looking the parent up by slug.
662
- *
663
- * @param parentSlug - The parent tag slug (null/empty for root)
664
- * @param context - Optional context for the parent lookup. When
665
- * omitted, the parent slug must be unambiguous across contexts.
666
- * @returns The calculated level (root parent → 1, missing parent → 0)
667
- */
668
- async calculateLevel(parentSlug, context) {
669
- if (!parentSlug) return 0;
670
- const parent = await this.resolveBySlug(parentSlug, context);
671
- if (!parent) return 0;
672
- return parent.level + 1;
673
- }
674
- /**
675
- * Update levels for all descendants after moving a tag
676
- *
677
- * @param tag - The tag that was moved
678
- */
679
- async updateDescendantLevels(tag) {
680
- if (!tag.id) return;
681
- const children = await this.list({ where: { parentId: tag.id } });
682
- for (const child of children) {
683
- child.level = tag.level + 1;
684
- await child.save();
685
- await this.updateDescendantLevels(child);
686
- }
687
- }
688
- /**
689
- * Find all tags belonging to a specific tenant
690
- *
691
- * @param tenantId - The tenant ID to filter by
692
- * @returns Array of tags for the specified tenant
693
- */
694
- async findByTenant(tenantId) {
695
- return this.list({ where: { tenantId } });
696
- }
697
- /**
698
- * Find all global (tenant-less) tags.
699
- *
700
- * Routes through the shared tenant-global helper so it does not throw under
701
- * an active tenant context (an explicit `tenant_id IS NULL` filter would be
702
- * flagged as an isolation violation). (#1600)
703
- *
704
- * @returns Array of global tags with null tenantId
705
- */
706
- async findGlobal() {
707
- return queryGlobal(this);
708
- }
709
- /**
710
- * Find tags for a tenant including global tags.
711
- *
712
- * Fails closed if an active tenant context requests a different tenant's
713
- * rows; the admin/system path keeps the cross-tenant capability. (#1600)
714
- *
715
- * @param tenantId - The tenant ID to filter by
716
- * @returns Array of tags for the tenant plus all global tags
717
- */
718
- async findWithGlobals(tenantId) {
719
- return queryWithGlobals(this, tenantId, "Tag.findWithGlobals");
720
- }
721
- };
722
- //#endregion
723
- //#region ../assets/dist/index.js
724
- var __defProp$9 = Object.defineProperty;
725
- var __exportAll = (all, no_symbols) => {
726
- let target = {};
727
- for (var name in all) __defProp$9(target, name, {
728
- get: all[name],
729
- enumerable: true
730
- });
731
- if (!no_symbols) __defProp$9(target, Symbol.toStringTag, { value: "Module" });
732
- return target;
733
- };
734
- ObjectRegistry.registerPackageManifest(JSON.parse(`{"version":"1.0.0","timestamp":0,"packageName":"@happyvertical/smrt-assets","packageVersion":"0.55.9","objects":{"@happyvertical/smrt-assets:AssetAssociation":{"name":"assetassociation","className":"AssetAssociation","qualifiedName":"@happyvertical/smrt-assets:AssetAssociation","collection":"assetassociations","filePath":"/home/runner/work/smrt/smrt/packages/assets/src/asset-association.ts","packageName":"@happyvertical/smrt-assets","fields":{"metaType":{"type":"text","required":true,"_meta":{"required":true}},"metaId":{"type":"text","required":true,"_meta":{"required":true}},"role":{"type":"text","required":true,"_meta":{"required":true}},"sortOrder":{"type":"integer","required":false,"default":0},"tenantId":{"type":"text","required":false,"_meta":{"sqlType":"UUID","nullable":true,"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":false,"autoPopulate":true,"nullable":true,"mode":"optional","field":"tenantId","allowSuperAdminBypass":false}}},"assetId":{"type":"foreignKey","required":true,"related":"Asset","_meta":{"required":true}}},"methods":{"hydrate":{"name":"hydrate","async":true,"parameters":[],"returnType":"Promise<T | null>","isStatic":false,"isPublic":true}},"decoratorConfig":{"conflictColumns":["asset_id","meta_type","meta_id","role"],"api":{"include":["list","get","create","delete"]},"mcp":{"include":["list","get","create"]},"cli":{"skipApiCheck":true},"tenantScoped":{"mode":"optional"}},"extends":"SmrtPolymorphicAssociation","exportName":"AssetAssociation","collectionExportName":"AssetAssociationCollection","validationRules":[{"field":"metaType","rule":"required","fieldType":"text"},{"field":"metaId","rule":"required","fieldType":"text"},{"field":"role","rule":"required","fieldType":"text"},{"field":"assetId","rule":"required","fieldType":"foreignKey"}],"schema":{"tableName":"asset_associations","ddl":"CREATE TABLE IF NOT EXISTS \\"asset_associations\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"meta_type\\" TEXT NOT NULL,\\n \\"meta_id\\" TEXT NOT NULL,\\n \\"role\\" TEXT NOT NULL,\\n \\"sort_order\\" INTEGER DEFAULT 0,\\n \\"tenant_id\\" UUID,\\n \\"asset_id\\" UUID NOT NULL\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"meta_type":{"type":"TEXT","notNull":true,"unique":false},"meta_id":{"type":"TEXT","notNull":true,"unique":false},"role":{"type":"TEXT","notNull":true,"unique":false},"sort_order":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"asset_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"assets","column":"id","onDelete":"CASCADE","onUpdate":"CASCADE"}}},"indexes":[{"name":"asset_associations_asset_id_meta_type_idx","columns":["asset_id","meta_type","meta_id","role"],"unique":true},{"name":"asset_associations_slug_context_idx","columns":["slug","context"]},{"name":"asset_associations_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"asset_associations_meta_type_meta_id_idx","columns":["meta_type","meta_id"]}],"version":"faa13cea"},"importPath":"@happyvertical/smrt-assets"},"@happyvertical/smrt-assets:AssetAssociationCollection":{"name":"assetassociationcollection","className":"AssetAssociationCollection","qualifiedName":"@happyvertical/smrt-assets:AssetAssociationCollection","collection":"assetassociations","filePath":"/home/runner/work/smrt/smrt/packages/assets/src/asset-associations.ts","packageName":"@happyvertical/smrt-assets","fields":{},"methods":{"byRight":{"name":"byRight","async":true,"parameters":[{"name":"rightId","type":"string","optional":false},{"name":"opts","type":"JunctionFilterOptions","optional":true}],"returnType":"Promise<TItem[]>","isStatic":false,"isPublic":true},"byLeft":{"name":"byLeft","async":true,"parameters":[{"name":"metaType","type":"string","optional":false},{"name":"metaId","type":"string","optional":false},{"name":"opts","type":"JunctionFilterOptions","optional":true}],"returnType":"Promise<AssetAssociation[]>","isStatic":false,"isPublic":true},"attach":{"name":"attach","async":true,"parameters":[{"name":"metaType","type":"string","optional":false},{"name":"metaId","type":"string","optional":false},{"name":"assetId","type":"string","optional":false},{"name":"opts","type":"JunctionAttachOptions","optional":true}],"returnType":"Promise<AssetAssociation>","isStatic":false,"isPublic":true},"detach":{"name":"detach","async":true,"parameters":[{"name":"metaType","type":"string","optional":false},{"name":"metaId","type":"string","optional":false},{"name":"assetId","type":"string","optional":false},{"name":"opts","type":"JunctionFilterOptions","optional":true}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"setLinks":{"name":"setLinks","async":true,"parameters":[{"name":"metaType","type":"string","optional":false},{"name":"metaId","type":"string","optional":false},{"name":"assetIds","type":"string[]","optional":false},{"name":"opts","type":"JunctionAttachOptions","optional":true}],"returnType":"Promise<void>","isStatic":false,"isPublic":true}},"decoratorConfig":{},"extends":"SmrtJunctionBase","extendsTypeArg":"AssetAssociation","exportName":"AssetAssociationCollection","collectionExportName":"AssetAssociationCollectionCollection","schema":{"tableName":"asset_associations","ddl":"CREATE TABLE IF NOT EXISTS \\"asset_associations\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"meta_type\\" TEXT NOT NULL,\\n \\"meta_id\\" TEXT NOT NULL,\\n \\"role\\" TEXT NOT NULL,\\n \\"sort_order\\" INTEGER DEFAULT 0,\\n \\"tenant_id\\" UUID,\\n \\"asset_id\\" UUID NOT NULL\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"meta_type":{"type":"TEXT","notNull":true,"unique":false},"meta_id":{"type":"TEXT","notNull":true,"unique":false},"role":{"type":"TEXT","notNull":true,"unique":false},"sort_order":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"asset_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"assets","column":"id","onDelete":"CASCADE","onUpdate":"CASCADE"}}},"indexes":[{"name":"asset_associations_asset_id_meta_type_idx","columns":["asset_id","meta_type","meta_id","role"],"unique":true},{"name":"asset_associations_slug_context_idx","columns":["slug","context"]},{"name":"asset_associations_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"asset_associations_meta_type_meta_id_idx","columns":["meta_type","meta_id"]}],"version":"faa13cea"},"importPath":"@happyvertical/smrt-assets"},"@happyvertical/smrt-assets:AssetMetafield":{"name":"assetmetafield","className":"AssetMetafield","qualifiedName":"@happyvertical/smrt-assets:AssetMetafield","collection":"assetmetafields","filePath":"/home/runner/work/smrt/smrt/packages/assets/src/asset-metafield.ts","packageName":"@happyvertical/smrt-assets","fields":{"created_at":{"type":"datetime","required":false},"updated_at":{"type":"datetime","required":false},"name":{"type":"text","required":false},"validation":{"type":"text","required":false}},"methods":{"getValidation":{"name":"getValidation","async":false,"parameters":[],"returnType":"Record<string, unknown>","isStatic":false,"isPublic":true},"setValidation":{"name":"setValidation","async":false,"parameters":[{"name":"rules","type":"Record<string, unknown>","optional":false}],"returnType":"void","isStatic":false,"isPublic":true},"getBySlug":{"name":"getBySlug","async":true,"parameters":[{"name":"_slug","type":"string","optional":false}],"returnType":"Promise<AssetMetafield | null>","isStatic":true,"isPublic":true}},"decoratorConfig":{"tableStrategy":"sti","api":{"include":["list","get","create","update","delete"]},"mcp":{"include":["list","get","create"]},"cli":{"skipApiCheck":true}},"extends":"SmrtObject","exportName":"AssetMetafield","collectionExportName":"AssetMetafieldCollection","displayLabelField":"name","schema":{"tableName":"asset_metafields","ddl":"CREATE TABLE IF NOT EXISTS \\"asset_metafields\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"_meta_type\\" TEXT NOT NULL,\\n \\"_meta_data\\" JSON,\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"name\\" TEXT,\\n \\"validation\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"_meta_type":{"type":"TEXT","notNull":true},"_meta_data":{"type":"JSON","notNull":false},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"name":{"type":"TEXT","notNull":false},"validation":{"type":"TEXT","notNull":false}},"indexes":[{"name":"asset_metafields_slug_context_meta_type_idx","columns":["slug","context","_meta_type"],"unique":true},{"name":"asset_metafields_meta_type_idx","columns":["_meta_type"]},{"name":"asset_metafields_created_at_idx","columns":["created_at"]}],"version":"7393718c"},"importPath":"@happyvertical/smrt-assets"},"@happyvertical/smrt-assets:AssetMetafieldCollection":{"name":"assetmetafieldcollection","className":"AssetMetafieldCollection","qualifiedName":"@happyvertical/smrt-assets:AssetMetafieldCollection","collection":"assetmetafields","filePath":"/home/runner/work/smrt/smrt/packages/assets/src/asset-metafields.ts","packageName":"@happyvertical/smrt-assets","fields":{},"methods":{"getOrCreate":{"name":"getOrCreate","async":true,"parameters":[{"name":"slug","type":"string","optional":false},{"name":"name","type":"string","optional":true},{"name":"validation","type":"string | Record<string, unknown>","optional":true,"unionBranches":[{"type":"string"},{"type":"Record<string, unknown>"}]}],"returnType":"Promise<AssetMetafield>","isStatic":false,"isPublic":true},"initializeCommonMetafields":{"name":"initializeCommonMetafields","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true}},"decoratorConfig":{},"extends":"SmrtCollection","extendsTypeArg":"AssetMetafield","exportName":"AssetMetafieldCollection","collectionExportName":"AssetMetafieldCollectionCollection","schema":{"tableName":"asset_metafields","ddl":"CREATE TABLE IF NOT EXISTS \\"asset_metafields\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"_meta_type\\" TEXT NOT NULL,\\n \\"_meta_data\\" JSON,\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"name\\" TEXT,\\n \\"validation\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"_meta_type":{"type":"TEXT","notNull":true},"_meta_data":{"type":"JSON","notNull":false},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"name":{"type":"TEXT","notNull":false},"validation":{"type":"TEXT","notNull":false}},"indexes":[{"name":"asset_metafields_slug_context_meta_type_idx","columns":["slug","context","_meta_type"],"unique":true},{"name":"asset_metafields_meta_type_idx","columns":["_meta_type"]},{"name":"asset_metafields_created_at_idx","columns":["created_at"]}],"version":"7393718c"},"importPath":"@happyvertical/smrt-assets"},"@happyvertical/smrt-assets:AssetStatus":{"name":"assetstatus","className":"AssetStatus","qualifiedName":"@happyvertical/smrt-assets:AssetStatus","collection":"assetstatuses","filePath":"/home/runner/work/smrt/smrt/packages/assets/src/asset-status.ts","packageName":"@happyvertical/smrt-assets","fields":{"created_at":{"type":"datetime","required":false},"updated_at":{"type":"datetime","required":false},"name":{"type":"text","required":false},"description":{"type":"text","required":false}},"methods":{"getBySlug":{"name":"getBySlug","async":true,"parameters":[{"name":"_slug","type":"string","optional":false}],"returnType":"Promise<AssetStatus | null>","isStatic":true,"isPublic":true}},"decoratorConfig":{"tableStrategy":"sti","api":{"include":["list","get","create","update","delete"]},"mcp":{"include":["list","get","create"]},"cli":{"skipApiCheck":true}},"extends":"SmrtObject","exportName":"AssetStatus","collectionExportName":"AssetStatusCollection","displayLabelField":"name","schema":{"tableName":"asset_statuses","ddl":"CREATE TABLE IF NOT EXISTS \\"asset_statuses\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"_meta_type\\" TEXT NOT NULL,\\n \\"_meta_data\\" JSON,\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"name\\" TEXT,\\n \\"description\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"_meta_type":{"type":"TEXT","notNull":true},"_meta_data":{"type":"JSON","notNull":false},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"name":{"type":"TEXT","notNull":false},"description":{"type":"TEXT","notNull":false}},"indexes":[{"name":"asset_statuses_slug_context_meta_type_idx","columns":["slug","context","_meta_type"],"unique":true},{"name":"asset_statuses_meta_type_idx","columns":["_meta_type"]},{"name":"asset_statuses_created_at_idx","columns":["created_at"]}],"version":"8251a52f"},"importPath":"@happyvertical/smrt-assets"},"@happyvertical/smrt-assets:AssetStatusCollection":{"name":"assetstatuscollection","className":"AssetStatusCollection","qualifiedName":"@happyvertical/smrt-assets:AssetStatusCollection","collection":"assetstatuses","filePath":"/home/runner/work/smrt/smrt/packages/assets/src/asset-statuses.ts","packageName":"@happyvertical/smrt-assets","fields":{},"methods":{"getOrCreate":{"name":"getOrCreate","async":true,"parameters":[{"name":"slug","type":"string","optional":false},{"name":"name","type":"string","optional":true},{"name":"description","type":"string","optional":true}],"returnType":"Promise<AssetStatus>","isStatic":false,"isPublic":true},"initializeCommonStatuses":{"name":"initializeCommonStatuses","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true}},"decoratorConfig":{},"extends":"SmrtCollection","extendsTypeArg":"AssetStatus","exportName":"AssetStatusCollection","collectionExportName":"AssetStatusCollectionCollection","schema":{"tableName":"asset_statuses","ddl":"CREATE TABLE IF NOT EXISTS \\"asset_statuses\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"_meta_type\\" TEXT NOT NULL,\\n \\"_meta_data\\" JSON,\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"name\\" TEXT,\\n \\"description\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"_meta_type":{"type":"TEXT","notNull":true},"_meta_data":{"type":"JSON","notNull":false},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"name":{"type":"TEXT","notNull":false},"description":{"type":"TEXT","notNull":false}},"indexes":[{"name":"asset_statuses_slug_context_meta_type_idx","columns":["slug","context","_meta_type"],"unique":true},{"name":"asset_statuses_meta_type_idx","columns":["_meta_type"]},{"name":"asset_statuses_created_at_idx","columns":["created_at"]}],"version":"8251a52f"},"importPath":"@happyvertical/smrt-assets"},"@happyvertical/smrt-assets:AssetTag":{"name":"assettag","className":"AssetTag","qualifiedName":"@happyvertical/smrt-assets:AssetTag","collection":"assettags","filePath":"/home/runner/work/smrt/smrt/packages/assets/src/asset-tag.ts","packageName":"@happyvertical/smrt-assets","fields":{"tenantId":{"type":"text","required":false,"_meta":{"sqlType":"UUID","nullable":true,"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":false,"autoPopulate":true,"nullable":true,"mode":"optional","field":"tenantId","allowSuperAdminBypass":false}}},"assetId":{"type":"foreignKey","required":true,"related":"Asset","_meta":{"required":true,"onDelete":"CASCADE"}},"tagId":{"type":"crossPackageRef","required":true,"related":"@happyvertical/smrt-tags:Tag","_meta":{"onDelete":"CASCADE"}}},"methods":{},"decoratorConfig":{"tableName":"asset_tags","conflictColumns":["asset_id","tag_id"],"api":false,"mcp":false,"cli":false,"tenantScoped":{"mode":"optional"}},"extends":"SmrtObject","exportName":"AssetTag","collectionExportName":"AssetTagCollection","validationRules":[{"field":"assetId","rule":"required","fieldType":"foreignKey"},{"field":"tagId","rule":"required","fieldType":"crossPackageRef"}],"schema":{"tableName":"asset_tags","ddl":"CREATE TABLE IF NOT EXISTS \\"asset_tags\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID,\\n \\"asset_id\\" UUID NOT NULL,\\n \\"tag_id\\" UUID NOT NULL\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"asset_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"assets","column":"id","onDelete":"CASCADE","onUpdate":"CASCADE"}},"tag_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false}},"indexes":[{"name":"asset_tags_asset_id_tag_id_idx","columns":["asset_id","tag_id"],"unique":true},{"name":"asset_tags_slug_context_idx","columns":["slug","context"]},{"name":"asset_tags_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"asset_tags_tag_id_idx","columns":["tag_id"]}],"version":"e60d24f5"},"importPath":"@happyvertical/smrt-assets"},"@happyvertical/smrt-assets:AssetTagCollection":{"name":"assettagcollection","className":"AssetTagCollection","qualifiedName":"@happyvertical/smrt-assets:AssetTagCollection","collection":"assettags","filePath":"/home/runner/work/smrt/smrt/packages/assets/src/asset-tags.ts","packageName":"@happyvertical/smrt-assets","fields":{},"methods":{"byRight":{"name":"byRight","async":true,"parameters":[{"name":"rightId","type":"string","optional":false},{"name":"opts","type":"JunctionFilterOptions","optional":true}],"returnType":"Promise<TItem[]>","isStatic":false,"isPublic":true},"byLeft":{"name":"byLeft","async":true,"parameters":[{"name":"leftId","type":"string","optional":false},{"name":"opts","type":"JunctionFilterOptions","optional":true}],"returnType":"Promise<TItem[]>","isStatic":false,"isPublic":true},"attach":{"name":"attach","async":true,"parameters":[{"name":"leftId","type":"string","optional":false},{"name":"rightId","type":"string","optional":false},{"name":"opts","type":"JunctionAttachOptions","optional":true}],"returnType":"Promise<TItem>","isStatic":false,"isPublic":true},"detach":{"name":"detach","async":true,"parameters":[{"name":"leftId","type":"string","optional":false},{"name":"rightId","type":"string","optional":false},{"name":"opts","type":"JunctionFilterOptions","optional":true}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"setLinks":{"name":"setLinks","async":true,"parameters":[{"name":"leftId","type":"string","optional":false},{"name":"rightIds","type":"string[]","optional":false},{"name":"opts","type":"JunctionAttachOptions","optional":true}],"returnType":"Promise<void>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"asset_tags","api":false,"mcp":false,"cli":false},"extends":"SmrtJunction","extendsTypeArg":"AssetTag","exportName":"AssetTagCollection","collectionExportName":"AssetTagCollectionCollection","schema":{"tableName":"asset_tags","ddl":"CREATE TABLE IF NOT EXISTS \\"asset_tags\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID,\\n \\"asset_id\\" UUID NOT NULL,\\n \\"tag_id\\" UUID NOT NULL\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"asset_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"assets","column":"id","onDelete":"CASCADE","onUpdate":"CASCADE"}},"tag_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false}},"indexes":[{"name":"asset_tags_asset_id_tag_id_idx","columns":["asset_id","tag_id"],"unique":true},{"name":"asset_tags_slug_context_idx","columns":["slug","context"]},{"name":"asset_tags_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"asset_tags_tag_id_idx","columns":["tag_id"]}],"version":"e60d24f5"},"importPath":"@happyvertical/smrt-assets"},"@happyvertical/smrt-assets:AssetType":{"name":"assettype","className":"AssetType","qualifiedName":"@happyvertical/smrt-assets:AssetType","collection":"assettypes","filePath":"/home/runner/work/smrt/smrt/packages/assets/src/asset-type.ts","packageName":"@happyvertical/smrt-assets","fields":{"created_at":{"type":"datetime","required":false},"updated_at":{"type":"datetime","required":false},"name":{"type":"text","required":false},"description":{"type":"text","required":false}},"methods":{"getBySlug":{"name":"getBySlug","async":true,"parameters":[{"name":"_slug","type":"string","optional":false}],"returnType":"Promise<AssetType | null>","isStatic":true,"isPublic":true}},"decoratorConfig":{"tableStrategy":"sti","api":{"include":["list","get","create","update","delete"]},"mcp":{"include":["list","get","create"]},"cli":{"skipApiCheck":true}},"extends":"SmrtObject","exportName":"AssetType","collectionExportName":"AssetTypeCollection","displayLabelField":"name","schema":{"tableName":"asset_types","ddl":"CREATE TABLE IF NOT EXISTS \\"asset_types\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"_meta_type\\" TEXT NOT NULL,\\n \\"_meta_data\\" JSON,\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"name\\" TEXT,\\n \\"description\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"_meta_type":{"type":"TEXT","notNull":true},"_meta_data":{"type":"JSON","notNull":false},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"name":{"type":"TEXT","notNull":false},"description":{"type":"TEXT","notNull":false}},"indexes":[{"name":"asset_types_slug_context_meta_type_idx","columns":["slug","context","_meta_type"],"unique":true},{"name":"asset_types_meta_type_idx","columns":["_meta_type"]},{"name":"asset_types_created_at_idx","columns":["created_at"]}],"version":"a9c93be2"},"importPath":"@happyvertical/smrt-assets"},"@happyvertical/smrt-assets:AssetTypeCollection":{"name":"assettypecollection","className":"AssetTypeCollection","qualifiedName":"@happyvertical/smrt-assets:AssetTypeCollection","collection":"assettypes","filePath":"/home/runner/work/smrt/smrt/packages/assets/src/asset-types.ts","packageName":"@happyvertical/smrt-assets","fields":{},"methods":{"getOrCreate":{"name":"getOrCreate","async":true,"parameters":[{"name":"slug","type":"string","optional":false},{"name":"name","type":"string","optional":true},{"name":"description","type":"string","optional":true}],"returnType":"Promise<AssetType>","isStatic":false,"isPublic":true},"initializeCommonTypes":{"name":"initializeCommonTypes","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true}},"decoratorConfig":{},"extends":"SmrtCollection","extendsTypeArg":"AssetType","exportName":"AssetTypeCollection","collectionExportName":"AssetTypeCollectionCollection","schema":{"tableName":"asset_types","ddl":"CREATE TABLE IF NOT EXISTS \\"asset_types\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"_meta_type\\" TEXT NOT NULL,\\n \\"_meta_data\\" JSON,\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"name\\" TEXT,\\n \\"description\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"_meta_type":{"type":"TEXT","notNull":true},"_meta_data":{"type":"JSON","notNull":false},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"name":{"type":"TEXT","notNull":false},"description":{"type":"TEXT","notNull":false}},"indexes":[{"name":"asset_types_slug_context_meta_type_idx","columns":["slug","context","_meta_type"],"unique":true},{"name":"asset_types_meta_type_idx","columns":["_meta_type"]},{"name":"asset_types_created_at_idx","columns":["created_at"]}],"version":"a9c93be2"},"importPath":"@happyvertical/smrt-assets"},"@happyvertical/smrt-assets:Asset":{"name":"asset","className":"Asset","qualifiedName":"@happyvertical/smrt-assets:Asset","collection":"assets","filePath":"/home/runner/work/smrt/smrt/packages/assets/src/asset.ts","packageName":"@happyvertical/smrt-assets","fields":{"created_at":{"type":"datetime","required":false},"updated_at":{"type":"datetime","required":false},"tenantId":{"type":"text","required":false,"_meta":{"sqlType":"UUID","nullable":true,"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":false,"autoPopulate":true,"nullable":true,"mode":"optional","field":"tenantId","allowSuperAdminBypass":false}}},"name":{"type":"text","required":false},"sourceUri":{"type":"text","required":false},"mimeType":{"type":"text","required":false},"description":{"type":"text","required":false},"metadata":{"type":"text","required":false},"version":{"type":"integer","required":true,"default":1},"primaryVersionId":{"type":"foreignKey","required":false,"related":"Asset"},"typeSlug":{"type":"text","required":false},"statusSlug":{"type":"text","required":false},"ownerProfileId":{"type":"crossPackageRef","required":false,"related":"@happyvertical/smrt-profiles:Profile"},"sourceAssetId":{"type":"foreignKey","required":false,"related":"Asset"},"folderId":{"type":"foreignKey","required":false,"related":"Folder"},"sourceType":{"type":"text","required":false},"externalId":{"type":"text","required":false},"externalRefs":{"type":"text","required":false},"createdAt":{"type":"text","required":false},"updatedAt":{"type":"text","required":false}},"methods":{"getSlug":{"name":"getSlug","async":true,"parameters":[],"returnType":"Promise<string | null | undefined>","isStatic":false,"isPublic":true},"getMetadata":{"name":"getMetadata","async":false,"parameters":[],"returnType":"Record<string, unknown>","isStatic":false,"isPublic":true},"setMetadata":{"name":"setMetadata","async":false,"parameters":[{"name":"metadata","type":"Record<string, unknown>","optional":false}],"returnType":"void","isStatic":false,"isPublic":true},"mergeMetadata":{"name":"mergeMetadata","async":false,"parameters":[{"name":"metadata","type":"Record<string, unknown>","optional":false}],"returnType":"void","isStatic":false,"isPublic":true},"getExternalRefs":{"name":"getExternalRefs","async":false,"parameters":[],"returnType":"Record<string, AssetExternalReference>","isStatic":false,"isPublic":true},"getExternalRef":{"name":"getExternalRef","async":false,"parameters":[{"name":"provider","type":"string","optional":false}],"returnType":"AssetExternalReference | null","isStatic":false,"isPublic":true},"setExternalRef":{"name":"setExternalRef","async":false,"parameters":[{"name":"provider","type":"string","optional":false},{"name":"reference","type":"any","optional":false,"typeUnresolved":true}],"returnType":"void","isStatic":false,"isPublic":true},"getTags":{"name":"getTags","async":true,"parameters":[],"returnType":"Promise<Tag[]>","isStatic":false,"isPublic":true},"hasTag":{"name":"hasTag","async":true,"parameters":[{"name":"tagSlug","type":"string","optional":false},{"name":"context","type":"string","optional":true}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true},"getSource":{"name":"getSource","async":true,"parameters":[],"returnType":"Promise<Asset | null>","isStatic":false,"isPublic":true},"getDerivatives":{"name":"getDerivatives","async":true,"parameters":[],"returnType":"Promise<Asset[]>","isStatic":false,"isPublic":true},"getType":{"name":"getType","async":true,"parameters":[],"returnType":"Promise<AssetType | null>","isStatic":false,"isPublic":true},"getStatus":{"name":"getStatus","async":true,"parameters":[],"returnType":"Promise<AssetStatus | null>","isStatic":false,"isPublic":true},"getAssociations":{"name":"getAssociations","async":true,"parameters":[],"returnType":"Promise<AssetAssociation[]>","isStatic":false,"isPublic":true},"associateWith":{"name":"associateWith","async":true,"parameters":[{"name":"metaType","type":"string","optional":false},{"name":"metaId","type":"string","optional":false},{"name":"role","type":"any","optional":true,"default":"default"}],"returnType":"Promise<AssetAssociation>","isStatic":false,"isPublic":true},"getBySlug":{"name":"getBySlug","async":true,"parameters":[{"name":"_slug","type":"string","optional":false}],"returnType":"Promise<Asset | null>","isStatic":true,"isPublic":true}},"decoratorConfig":{"tableStrategy":"sti","api":{"include":["list","get","create","update","delete"]},"mcp":{"include":["list","get","create","update"]},"cli":{"skipApiCheck":true},"tenantScoped":{"mode":"optional"},"conflictColumns":["tenant_id","slug","context","_meta_type"]},"extends":"SmrtObject","exportName":"Asset","collectionExportName":"AssetCollection","displayLabelField":"name","validationRules":[{"field":"version","rule":"required","fieldType":"integer"}],"schema":{"tableName":"assets","ddl":"CREATE TABLE IF NOT EXISTS \\"assets\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"_meta_type\\" TEXT NOT NULL,\\n \\"_meta_data\\" JSON,\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID,\\n \\"name\\" TEXT,\\n \\"source_uri\\" TEXT,\\n \\"mime_type\\" TEXT,\\n \\"description\\" TEXT,\\n \\"metadata\\" TEXT,\\n \\"version\\" INTEGER DEFAULT 1,\\n \\"primary_version_id\\" UUID,\\n \\"type_slug\\" TEXT,\\n \\"status_slug\\" TEXT,\\n \\"owner_profile_id\\" UUID,\\n \\"source_asset_id\\" UUID,\\n \\"folder_id\\" UUID,\\n \\"source_type\\" TEXT,\\n \\"external_id\\" TEXT,\\n \\"external_refs\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"_meta_type":{"type":"TEXT","notNull":true},"_meta_data":{"type":"JSON","notNull":false},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false},"name":{"type":"TEXT","notNull":false},"source_uri":{"type":"TEXT","notNull":false},"mime_type":{"type":"TEXT","notNull":false},"description":{"type":"TEXT","notNull":false},"metadata":{"type":"TEXT","notNull":false},"version":{"type":"INTEGER","notNull":false,"default":1},"primary_version_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"foreignKey":{"table":"assets","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"type_slug":{"type":"TEXT","notNull":false},"status_slug":{"type":"TEXT","notNull":false},"owner_profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false},"source_asset_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"foreignKey":{"table":"assets","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"folder_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"foreignKey":{"table":"folders","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"source_type":{"type":"TEXT","notNull":false},"external_id":{"type":"TEXT","notNull":false},"external_refs":{"type":"TEXT","notNull":false}},"indexes":[{"name":"assets_slug_context_meta_type_idx","columns":["tenant_id","slug","context","_meta_type"],"unique":true,"nullsNotDistinct":true},{"name":"assets_meta_type_idx","columns":["_meta_type"]},{"name":"assets_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"assets_primary_version_id_idx","columns":["primary_version_id"]},{"name":"assets_owner_profile_id_idx","columns":["owner_profile_id"]},{"name":"assets_source_asset_id_idx","columns":["source_asset_id"]},{"name":"assets_folder_id_idx","columns":["folder_id"]}],"version":"16d6c152"},"importPath":"@happyvertical/smrt-assets"},"@happyvertical/smrt-assets:AssetCollection":{"name":"assetcollection","className":"AssetCollection","qualifiedName":"@happyvertical/smrt-assets:AssetCollection","collection":"assets","filePath":"/home/runner/work/smrt/smrt/packages/assets/src/assets.ts","packageName":"@happyvertical/smrt-assets","fields":{},"methods":{"findByTenant":{"name":"findByTenant","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<Asset[]>","isStatic":false,"isPublic":true},"findGlobal":{"name":"findGlobal","async":true,"parameters":[],"returnType":"Promise<Asset[]>","isStatic":false,"isPublic":true},"findWithGlobals":{"name":"findWithGlobals","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<Asset[]>","isStatic":false,"isPublic":true},"addTag":{"name":"addTag","async":true,"parameters":[{"name":"assetId","type":"string","optional":false},{"name":"tag","type":"string","optional":false},{"name":"options","type":"AssetTagInput","optional":true}],"returnType":"Promise<Tag>","isStatic":false,"isPublic":true},"removeTag":{"name":"removeTag","async":true,"parameters":[{"name":"assetId","type":"string","optional":false},{"name":"tag","type":"string","optional":false},{"name":"options","type":"Pick<AssetTagInput, 'context'>","optional":true}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"setTags":{"name":"setTags","async":true,"parameters":[{"name":"assetId","type":"string","optional":false},{"name":"tags","type":"string[]","optional":false},{"name":"options","type":"Pick<AssetTagInput, 'context'>","optional":true}],"returnType":"Promise<Tag[]>","isStatic":false,"isPublic":true},"getTagsForAssets":{"name":"getTagsForAssets","async":true,"parameters":[{"name":"assetIds","type":"string[]","optional":false}],"returnType":"Promise<Map<string, Tag[]>>","isStatic":false,"isPublic":true},"getByTag":{"name":"getByTag","async":true,"parameters":[{"name":"tag","type":"string","optional":false},{"name":"options","type":"Pick<AssetTagInput, 'context'>","optional":true}],"returnType":"Promise<Asset[]>","isStatic":false,"isPublic":true},"getByType":{"name":"getByType","async":true,"parameters":[{"name":"typeSlug","type":"string","optional":false}],"returnType":"Promise<Asset[]>","isStatic":false,"isPublic":true},"getByStatus":{"name":"getByStatus","async":true,"parameters":[{"name":"statusSlug","type":"string","optional":false}],"returnType":"Promise<Asset[]>","isStatic":false,"isPublic":true},"getByOwner":{"name":"getByOwner","async":true,"parameters":[{"name":"ownerProfileId","type":"string","optional":false}],"returnType":"Promise<Asset[]>","isStatic":false,"isPublic":true},"createNewVersion":{"name":"createNewVersion","async":true,"parameters":[{"name":"primaryVersionId","type":"string","optional":false},{"name":"newSourceUri","type":"string","optional":false},{"name":"updates","type":"Partial<Asset>","optional":true}],"returnType":"Promise<Asset>","isStatic":false,"isPublic":true},"getLatestVersion":{"name":"getLatestVersion","async":true,"parameters":[{"name":"primaryVersionId","type":"string","optional":false}],"returnType":"Promise<Asset | null>","isStatic":false,"isPublic":true},"listVersions":{"name":"listVersions","async":true,"parameters":[{"name":"primaryVersionId","type":"string","optional":false}],"returnType":"Promise<Asset[]>","isStatic":false,"isPublic":true},"getDerivatives":{"name":"getDerivatives","async":true,"parameters":[{"name":"sourceAssetId","type":"string","optional":false}],"returnType":"Promise<Asset[]>","isStatic":false,"isPublic":true},"getByMimeType":{"name":"getByMimeType","async":true,"parameters":[{"name":"mimePattern","type":"string","optional":false}],"returnType":"Promise<Asset[]>","isStatic":false,"isPublic":true},"rollbackToVersion":{"name":"rollbackToVersion","async":true,"parameters":[{"name":"primaryVersionId","type":"string","optional":false},{"name":"targetVersion","type":"number","optional":false}],"returnType":"Promise<Asset>","isStatic":false,"isPublic":true},"getByFolder":{"name":"getByFolder","async":true,"parameters":[{"name":"folderId","type":"string","optional":false}],"returnType":"Promise<Asset[]>","isStatic":false,"isPublic":true}},"decoratorConfig":{},"extends":"SmrtCollection","extendsTypeArg":"Asset","exportName":"AssetCollection","collectionExportName":"AssetCollectionCollection","schema":{"tableName":"assets","ddl":"CREATE TABLE IF NOT EXISTS \\"assets\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"_meta_type\\" TEXT NOT NULL,\\n \\"_meta_data\\" JSON,\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID,\\n \\"name\\" TEXT,\\n \\"source_uri\\" TEXT,\\n \\"mime_type\\" TEXT,\\n \\"description\\" TEXT,\\n \\"metadata\\" TEXT,\\n \\"version\\" INTEGER DEFAULT 1,\\n \\"primary_version_id\\" UUID,\\n \\"type_slug\\" TEXT,\\n \\"status_slug\\" TEXT,\\n \\"owner_profile_id\\" UUID,\\n \\"source_asset_id\\" UUID,\\n \\"folder_id\\" UUID,\\n \\"source_type\\" TEXT,\\n \\"external_id\\" TEXT,\\n \\"external_refs\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"_meta_type":{"type":"TEXT","notNull":true},"_meta_data":{"type":"JSON","notNull":false},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false},"name":{"type":"TEXT","notNull":false},"source_uri":{"type":"TEXT","notNull":false},"mime_type":{"type":"TEXT","notNull":false},"description":{"type":"TEXT","notNull":false},"metadata":{"type":"TEXT","notNull":false},"version":{"type":"INTEGER","notNull":false,"default":1},"primary_version_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"foreignKey":{"table":"assets","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"type_slug":{"type":"TEXT","notNull":false},"status_slug":{"type":"TEXT","notNull":false},"owner_profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false},"source_asset_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"foreignKey":{"table":"assets","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"folder_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"foreignKey":{"table":"folders","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"source_type":{"type":"TEXT","notNull":false},"external_id":{"type":"TEXT","notNull":false},"external_refs":{"type":"TEXT","notNull":false}},"indexes":[{"name":"assets_slug_context_meta_type_idx","columns":["tenant_id","slug","context","_meta_type"],"unique":true,"nullsNotDistinct":true},{"name":"assets_meta_type_idx","columns":["_meta_type"]},{"name":"assets_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"assets_primary_version_id_idx","columns":["primary_version_id"]},{"name":"assets_owner_profile_id_idx","columns":["owner_profile_id"]},{"name":"assets_source_asset_id_idx","columns":["source_asset_id"]},{"name":"assets_folder_id_idx","columns":["folder_id"]}],"version":"16d6c152"},"importPath":"@happyvertical/smrt-assets"},"@happyvertical/smrt-assets:Folder":{"name":"folder","className":"Folder","qualifiedName":"@happyvertical/smrt-assets:Folder","collection":"folders","filePath":"/home/runner/work/smrt/smrt/packages/assets/src/folder.ts","packageName":"@happyvertical/smrt-assets","fields":{"parentId":{"type":"foreignKey","required":false,"related":"Folder","_meta":{"nullable":true}},"tenantId":{"type":"text","required":false,"_meta":{"sqlType":"UUID","nullable":true,"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":false,"autoPopulate":true,"nullable":true,"mode":"optional","field":"tenantId","allowSuperAdminBypass":false}}},"name":{"type":"text","required":false},"description":{"type":"text","required":false},"ownerProfileId":{"type":"crossPackageRef","required":false,"related":"@happyvertical/smrt-profiles:Profile"},"createdAt":{"type":"text","required":false},"updatedAt":{"type":"text","required":false}},"methods":{"getParent":{"name":"getParent","async":true,"parameters":[],"returnType":"Promise<this | null>","isStatic":false,"isPublic":true},"getChildren":{"name":"getChildren","async":true,"parameters":[],"returnType":"Promise<this[]>","isStatic":false,"isPublic":true},"getAncestors":{"name":"getAncestors","async":true,"parameters":[],"returnType":"Promise<this[]>","isStatic":false,"isPublic":true},"getDescendants":{"name":"getDescendants","async":true,"parameters":[],"returnType":"Promise<this[]>","isStatic":false,"isPublic":true},"getHierarchy":{"name":"getHierarchy","async":true,"parameters":[],"returnType":"Promise<HierarchyView<this>>","isStatic":false,"isPublic":true},"moveTo":{"name":"moveTo","async":true,"parameters":[{"name":"newParent","type":"this | string | null","optional":false,"unionBranches":[{"type":"this"},{"type":"string"},{"type":"null"}]}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"getBySlug":{"name":"getBySlug","async":true,"parameters":[{"name":"_slug","type":"string","optional":false}],"returnType":"Promise<Folder | null>","isStatic":true,"isPublic":true}},"decoratorConfig":{"api":{"include":["list","get","create","update","delete"]},"mcp":{"include":["list","get","create","update"]},"cli":{"skipApiCheck":true},"tenantScoped":{"mode":"optional"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtHierarchical","exportName":"Folder","collectionExportName":"FolderCollection","displayLabelField":"name","schema":{"tableName":"folders","ddl":"CREATE TABLE IF NOT EXISTS \\"folders\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"parent_id\\" UUID,\\n \\"tenant_id\\" UUID,\\n \\"name\\" TEXT,\\n \\"description\\" TEXT,\\n \\"owner_profile_id\\" UUID\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"parent_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"folders","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"name":{"type":"TEXT","notNull":false,"unique":false},"description":{"type":"TEXT","notNull":false,"unique":false},"owner_profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false}},"indexes":[{"name":"folders_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"folders_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"folders_parent_id_idx","columns":["parent_id"]},{"name":"folders_owner_profile_id_idx","columns":["owner_profile_id"]}],"version":"1d0b1fcb"},"importPath":"@happyvertical/smrt-assets"},"@happyvertical/smrt-assets:FolderCollection":{"name":"foldercollection","className":"FolderCollection","qualifiedName":"@happyvertical/smrt-assets:FolderCollection","collection":"folders","filePath":"/home/runner/work/smrt/smrt/packages/assets/src/folders.ts","packageName":"@happyvertical/smrt-assets","fields":{},"methods":{"getTree":{"name":"getTree","async":true,"parameters":[{"name":"rootId","type":"string","optional":true}],"returnType":"Promise<Folder[]>","isStatic":false,"isPublic":true},"getPath":{"name":"getPath","async":true,"parameters":[{"name":"folderId","type":"string","optional":false}],"returnType":"Promise<Folder[]>","isStatic":false,"isPublic":true},"getContents":{"name":"getContents","async":true,"parameters":[{"name":"folderId","type":"string","optional":false},{"name":"assetCollection","type":"AssetCollection","optional":false}],"returnType":"Promise<Asset[]>","isStatic":false,"isPublic":true},"moveAsset":{"name":"moveAsset","async":true,"parameters":[{"name":"asset","type":"Asset","optional":false},{"name":"folderId","type":"string | null","optional":false,"unionBranches":[{"type":"string"},{"type":"null"}]}],"returnType":"Promise<void>","isStatic":false,"isPublic":true}},"decoratorConfig":{},"extends":"SmrtCollection","extendsTypeArg":"Folder","exportName":"FolderCollection","collectionExportName":"FolderCollectionCollection","schema":{"tableName":"folders","ddl":"CREATE TABLE IF NOT EXISTS \\"folders\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"parent_id\\" UUID,\\n \\"tenant_id\\" UUID,\\n \\"name\\" TEXT,\\n \\"description\\" TEXT,\\n \\"owner_profile_id\\" UUID\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"parent_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"folders","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"name":{"type":"TEXT","notNull":false,"unique":false},"description":{"type":"TEXT","notNull":false,"unique":false},"owner_profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false}},"indexes":[{"name":"folders_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"folders_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"folders_parent_id_idx","columns":["parent_id"]},{"name":"folders_owner_profile_id_idx","columns":["owner_profile_id"]}],"version":"1d0b1fcb"},"importPath":"@happyvertical/smrt-assets"}},"moduleType":"smrt","smrtDependencies":["@happyvertical/smrt-core","@happyvertical/smrt-tags","@happyvertical/smrt-tenancy"],"browser":{"status":"server-only","issues":["#3624"],"via":["@happyvertical/smrt-tenancy"]},"stampsConstructors":true}`));
735
- var __defProp$8 = Object.defineProperty;
736
- var __getOwnPropDesc$8 = Object.getOwnPropertyDescriptor;
737
- var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, {
738
- enumerable: true,
739
- configurable: true,
740
- writable: true,
741
- value
742
- }) : obj[key] = value;
743
- var __decorateClass$8 = (decorators, target, key, kind) => {
744
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$8(target, key) : target;
745
- for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
746
- if (kind && result) __defProp$8(target, key, result);
747
- return result;
748
- };
749
- var __publicField$8 = (obj, key, value) => __defNormalProp$8(obj, typeof key !== "symbol" ? key + "" : key, value);
750
- var AssetAssociation = class extends SmrtPolymorphicAssociation {
751
- tenantId = null;
752
- assetId = "";
753
- constructor(options = {}) {
754
- super(options);
755
- if (options.assetId) this.assetId = options.assetId;
756
- if (options.tenantId !== void 0) this.tenantId = options.tenantId;
757
- }
758
- };
759
- __publicField$8(AssetAssociation, "__smrtPackage__", "@happyvertical/smrt-assets");
760
- __decorateClass$8([tenantId({ nullable: true })], AssetAssociation.prototype, "tenantId", 2);
761
- __decorateClass$8([foreignKey("Asset", { required: true })], AssetAssociation.prototype, "assetId", 2);
762
- AssetAssociation = __decorateClass$8([TenantScoped({ mode: "optional" }), smrt({
763
- conflictColumns: [
764
- "asset_id",
765
- "meta_type",
766
- "meta_id",
767
- "role"
768
- ],
769
- api: { include: [
770
- "list",
771
- "get",
772
- "create",
773
- "delete"
774
- ] },
775
- mcp: { include: [
776
- "list",
777
- "get",
778
- "create"
779
- ] },
780
- cli: { skipApiCheck: true }
781
- })], AssetAssociation);
782
- var __defProp$7 = Object.defineProperty;
783
- var __getOwnPropDesc$7 = Object.getOwnPropertyDescriptor;
784
- var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, {
785
- enumerable: true,
786
- configurable: true,
787
- writable: true,
788
- value
789
- }) : obj[key] = value;
790
- var __decorateClass$7 = (decorators, target, key, kind) => {
791
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$7(target, key) : target;
792
- for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
793
- if (kind && result) __defProp$7(target, key, result);
794
- return result;
795
- };
796
- var __publicField$7 = (obj, key, value) => __defNormalProp$7(obj, typeof key !== "symbol" ? key + "" : key, value);
797
- async function metaTypeFilter(metaType) {
798
- const names = await ObjectRegistry.getEquivalentQualifiedNamesAsync(metaType, { source: "AssetAssociationCollection" });
799
- return names.length === 1 ? names[0] : names;
800
- }
801
- var AssetAssociationCollection = class extends SmrtJunctionBase {
802
- rightField = "assetId";
803
- /**
804
- * List associations for a polymorphic owner.
805
- *
806
- * Composite left key — pass both halves.
807
- */
808
- async byLeft(metaType, metaId, opts = {}) {
809
- return await this.list({
810
- where: {
811
- ...opts,
812
- metaType: await metaTypeFilter(metaType),
813
- metaId
814
- },
815
- orderBy: "sort_order ASC"
816
- });
817
- }
818
- /**
819
- * Create an association. Composite left (metaType, metaId) precedes right (assetId).
820
- */
821
- async attach(metaType, metaId, assetId, opts = {}) {
822
- return await this.create({
823
- ...opts,
824
- assetId,
825
- metaType,
826
- metaId
827
- });
828
- }
829
- /**
830
- * Delete matching associations. Composite left (metaType, metaId) precedes right (assetId).
831
- */
832
- async detach(metaType, metaId, assetId, opts = {}) {
833
- const links = await this.list({ where: {
834
- ...opts,
835
- metaType: await metaTypeFilter(metaType),
836
- metaId,
837
- assetId
838
- } });
839
- for (const link of links) await link.delete();
840
- }
841
- /**
842
- * Replace all associations for a polymorphic owner with the given asset IDs.
843
- * Not transactional — see `SmrtJunction.setLinks` for caveats.
844
- */
845
- async setLinks(metaType, metaId, assetIds, opts = {}) {
846
- const snapshotOpts = { ...opts };
847
- delete snapshotOpts.assetId;
848
- const existing = await this.list({ where: {
849
- ...snapshotOpts,
850
- metaType: await metaTypeFilter(metaType),
851
- metaId
852
- } });
853
- for (const link of existing) await link.delete();
854
- const positionKey = this.positionField;
855
- for (let i = 0; i < assetIds.length; i++) {
856
- const rowOpts = { ...opts };
857
- if (positionKey && rowOpts[positionKey] === void 0) rowOpts[positionKey] = i;
858
- await this.attach(metaType, metaId, assetIds[i], rowOpts);
859
- }
860
- }
861
- };
862
- __publicField$7(AssetAssociationCollection, "__smrtPackage__", "@happyvertical/smrt-assets");
863
- __publicField$7(AssetAssociationCollection, "_itemClass", AssetAssociation);
864
- AssetAssociationCollection = __decorateClass$7([smrt()], AssetAssociationCollection);
865
- var __defProp$6 = Object.defineProperty;
866
- var __getOwnPropDesc$6 = Object.getOwnPropertyDescriptor;
867
- var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, {
868
- enumerable: true,
869
- configurable: true,
870
- writable: true,
871
- value
872
- }) : obj[key] = value;
873
- var __decorateClass$6 = (decorators, target, key, kind) => {
874
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$6(target, key) : target;
875
- for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
876
- if (kind && result) __defProp$6(target, key, result);
877
- return result;
878
- };
879
- var __publicField$6 = (obj, key, value) => __defNormalProp$6(obj, typeof key !== "symbol" ? key + "" : key, value);
880
- var AssetStatus = class extends SmrtObject {
881
- name = "";
882
- description = "";
883
- constructor(options = {}) {
884
- super(options);
885
- if (options.slug) this.slug = options.slug;
886
- if (options.name) this.name = options.name;
887
- if (options.description) this.description = options.description;
888
- }
889
- /**
890
- * Get asset status by slug
891
- *
892
- * @param slug - The slug to search for
893
- * @returns AssetStatus instance or null
894
- */
895
- static async getBySlug(_slug) {
896
- return null;
897
- }
898
- };
899
- __publicField$6(AssetStatus, "__smrtPackage__", "@happyvertical/smrt-assets");
900
- AssetStatus = __decorateClass$6([smrt({
901
- tableStrategy: "sti",
902
- api: { include: [
903
- "list",
904
- "get",
905
- "create",
906
- "update",
907
- "delete"
908
- ] },
909
- mcp: { include: [
910
- "list",
911
- "get",
912
- "create"
913
- ] },
914
- cli: { skipApiCheck: true }
915
- })], AssetStatus);
916
- var __defProp$5 = Object.defineProperty;
917
- var __getOwnPropDesc$5 = Object.getOwnPropertyDescriptor;
918
- var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, {
919
- enumerable: true,
920
- configurable: true,
921
- writable: true,
922
- value
923
- }) : obj[key] = value;
924
- var __decorateClass$5 = (decorators, target, key, kind) => {
925
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$5(target, key) : target;
926
- for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
927
- if (kind && result) __defProp$5(target, key, result);
928
- return result;
929
- };
930
- var __publicField$5 = (obj, key, value) => __defNormalProp$5(obj, typeof key !== "symbol" ? key + "" : key, value);
931
- var AssetType = class extends SmrtObject {
932
- name = "";
933
- description = "";
934
- constructor(options = {}) {
935
- super(options);
936
- if (options.slug) this.slug = options.slug;
937
- if (options.name) this.name = options.name;
938
- if (options.description) this.description = options.description;
939
- }
940
- /**
941
- * Get asset type by slug
942
- *
943
- * @param slug - The slug to search for
944
- * @returns AssetType instance or null
945
- */
946
- static async getBySlug(_slug) {
947
- return null;
948
- }
949
- };
950
- __publicField$5(AssetType, "__smrtPackage__", "@happyvertical/smrt-assets");
951
- AssetType = __decorateClass$5([smrt({
952
- tableStrategy: "sti",
953
- api: { include: [
954
- "list",
955
- "get",
956
- "create",
957
- "update",
958
- "delete"
959
- ] },
960
- mcp: { include: [
961
- "list",
962
- "get",
963
- "create"
964
- ] },
965
- cli: { skipApiCheck: true }
966
- })], AssetType);
967
- var __defProp$4 = Object.defineProperty;
968
- var __getOwnPropDesc$4 = Object.getOwnPropertyDescriptor;
969
- var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, {
970
- enumerable: true,
971
- configurable: true,
972
- writable: true,
973
- value
974
- }) : obj[key] = value;
975
- var __decorateClass$4 = (decorators, target, key, kind) => {
976
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$4(target, key) : target;
977
- for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
978
- if (kind && result) __defProp$4(target, key, result);
979
- return result;
980
- };
981
- var __publicField$4 = (obj, key, value) => __defNormalProp$4(obj, typeof key !== "symbol" ? key + "" : key, value);
982
- function parseAssetRecord(value) {
983
- if (!value) return {};
984
- if (typeof value !== "string") return value;
985
- if (!value.trim()) return {};
986
- try {
987
- const parsed = JSON.parse(value);
988
- return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
989
- } catch {
990
- return {};
991
- }
992
- }
993
- function stringifyAssetRecord(value) {
994
- if (!value || Object.keys(value).length === 0) return "";
995
- return JSON.stringify(value);
996
- }
997
- var Asset = class extends SmrtObject {
998
- tenantId = null;
999
- name = "";
1000
- sourceUri = "";
1001
- mimeType = "";
1002
- description = "";
1003
- metadata = "";
1004
- version = 1;
1005
- primaryVersionId = null;
1006
- typeSlug = "";
1007
- statusSlug = "";
1008
- ownerProfileId = null;
1009
- sourceAssetId = null;
1010
- folderId = null;
1011
- sourceType = "";
1012
- externalId = "";
1013
- externalRefs = "";
1014
- createdAt = /* @__PURE__ */ new Date();
1015
- updatedAt = /* @__PURE__ */ new Date();
1016
- /**
1017
- * A file's name is not its identity: two pictures named "photo.jpg" are two
1018
- * assets. Without an explicit slug the default (name-derived) slug would
1019
- * make the second save adopt the first row through the (tenant, slug,
1020
- * context) natural key and overwrite it, so an asset's default slug is its
1021
- * id. An explicit slug is kept.
1022
- */
1023
- async getSlug() {
1024
- if (!this.slug && this.id) this.slug = String(this.id);
1025
- return super.getSlug();
1026
- }
1027
- constructor(options = {}) {
1028
- super(options);
1029
- if (options.name) this.name = options.name;
1030
- if (options.slug) this.slug = options.slug;
1031
- if (options.sourceUri) this.sourceUri = options.sourceUri;
1032
- if (options.mimeType) this.mimeType = options.mimeType;
1033
- if (options.description) this.description = options.description;
1034
- if (options.metadata !== void 0) this.metadata = typeof options.metadata === "string" ? options.metadata : stringifyAssetRecord(options.metadata);
1035
- if (options.version !== void 0) this.version = options.version;
1036
- if (options.primaryVersionId !== void 0) this.primaryVersionId = options.primaryVersionId;
1037
- if (options.typeSlug) this.typeSlug = options.typeSlug;
1038
- if (options.statusSlug) this.statusSlug = options.statusSlug;
1039
- if (options.ownerProfileId !== void 0) this.ownerProfileId = options.ownerProfileId;
1040
- if (options.sourceAssetId !== void 0) this.sourceAssetId = options.sourceAssetId;
1041
- if (options.folderId !== void 0) this.folderId = options.folderId;
1042
- if (options.sourceType) this.sourceType = options.sourceType;
1043
- if (options.externalId) this.externalId = options.externalId;
1044
- if (options.externalRefs !== void 0) this.externalRefs = typeof options.externalRefs === "string" ? options.externalRefs : stringifyAssetRecord(options.externalRefs);
1045
- if (options.tenantId !== void 0) this.tenantId = options.tenantId;
1046
- if (options.createdAt) this.createdAt = options.createdAt;
1047
- if (options.updatedAt) this.updatedAt = options.updatedAt;
1048
- }
1049
- getMetadata() {
1050
- return parseAssetRecord(this.metadata);
1051
- }
1052
- setMetadata(metadata) {
1053
- this.metadata = stringifyAssetRecord(metadata);
1054
- }
1055
- mergeMetadata(metadata) {
1056
- this.setMetadata({
1057
- ...this.getMetadata(),
1058
- ...metadata
1059
- });
1060
- }
1061
- getExternalRefs() {
1062
- const refs = parseAssetRecord(this.externalRefs);
1063
- const normalized = {};
1064
- for (const [provider, value] of Object.entries(refs)) if (value && typeof value === "object" && !Array.isArray(value)) normalized[provider] = {
1065
- ...value,
1066
- provider
1067
- };
1068
- return normalized;
1069
- }
1070
- getExternalRef(provider) {
1071
- return this.getExternalRefs()[provider] ?? null;
1072
- }
1073
- setExternalRef(provider, reference) {
1074
- this.externalRefs = stringifyAssetRecord({
1075
- ...this.getExternalRefs(),
1076
- [provider]: {
1077
- ...this.getExternalRef(provider) ?? {},
1078
- ...reference,
1079
- provider: reference.provider ?? provider
1080
- }
1081
- });
1082
- }
1083
- /**
1084
- * Get all tags for this asset from @happyvertical/smrt-tags, through the
1085
- * `asset_tags` join (`AssetTag`), sorted by name.
1086
- *
1087
- * @returns Array of Tag instances from @happyvertical/smrt-tags package
1088
- */
1089
- async getTags() {
1090
- if (!this.id) return [];
1091
- const { AssetTagCollection } = await Promise.resolve().then(() => asset_tags_exports);
1092
- const rows = await (await AssetTagCollection.create({ db: this.db })).byLeft(this.id);
1093
- if (rows.length === 0) return [];
1094
- return (await (await TagCollection.create({ db: this.db })).listByIds([...new Set(rows.map((row) => row.tagId))])).sort((a, b) => a.name.localeCompare(b.name));
1095
- }
1096
- /**
1097
- * Check if this asset has a specific tag
1098
- *
1099
- * @param tagSlug - The slug of the tag to check
1100
- * @param context - Tag context; any context when omitted
1101
- * @returns True if the asset has this tag
1102
- */
1103
- async hasTag(tagSlug, context) {
1104
- return (await this.getTags()).some((tag) => tag.slug === tagSlug && (context === void 0 || tag.context === context));
1105
- }
1106
- /**
1107
- * Resolve the AssetCollection lazily. Going through `ObjectRegistry`
1108
- * mirrors the pattern used by `SmrtHierarchical._hierarchyCollection`
1109
- * so source/derivative lookups inherit tenant scoping and ORM
1110
- * hydration without hard-coding an import of `./assets` (which would
1111
- * create a module-import cycle).
1112
- *
1113
- * The return type is `SmrtCollection<Asset>` (the framework base, type-
1114
- * only import from core) rather than the concrete `AssetCollection` —
1115
- * importing the concrete class is what would create the cycle, but the
1116
- * base-class shape gives callers full `.get()` / `.list()` type
1117
- * safety here.
1118
- *
1119
- * R5-canon: hardcode the base Asset's qualified key so a different
1120
- * package also registering a class called `Asset` can't be picked
1121
- * by `findClass`'s multi-strategy fallback. Crucially we DON'T
1122
- * resolve via `this.constructor._smrtQualifiedName` — for an STI
1123
- * subclass like `Image`, that would yield the Image collection
1124
- * (which auto-filters `_meta_type = '...:Image'` on `get`/`list`),
1125
- * and `getSource()` / `getDerivatives()` would miss cross-type
1126
- * derivation links (Image derived from a plain Asset, etc.).
1127
- * `sourceAssetId` is a base-table derivation link, so it always
1128
- * resolves through the base Asset collection.
1129
- */
1130
- async _assetCollection() {
1131
- return await ObjectRegistry.getCollection("@happyvertical/smrt-assets:Asset", this.options);
1132
- }
1133
- /**
1134
- * Get the source asset this one was derived from, if any.
1135
- *
1136
- * Renamed from `getParent` in R3-D. The relationship is "I was produced
1137
- * from that asset" (e.g. a thumbnail's source is its original image),
1138
- * not a structural-hierarchy parent.
1139
- *
1140
- * Goes through the AssetCollection so tenant interceptors and ORM
1141
- * hydration apply — important because a tenant-scoped consumer with
1142
- * cross-tenant derivative chains would otherwise return assets from
1143
- * tenants the caller cannot see, and a raw `db.get` returns
1144
- * snake_case rows that leave camelCase props (e.g. `sourceUri`) at
1145
- * their constructor defaults.
1146
- *
1147
- * @returns Source Asset instance, or null if this asset has no source
1148
- */
1149
- async getSource() {
1150
- if (!this.sourceAssetId) return null;
1151
- return await (await this._assetCollection()).get({ id: this.sourceAssetId });
1152
- }
1153
- /**
1154
- * Get all assets derived from this one (e.g. thumbnails, variants,
1155
- * transcodes, AI edits).
1156
- *
1157
- * Renamed from `getChildren` in R3-D to match the derivation
1158
- * semantics. Goes through the AssetCollection so tenant interceptors
1159
- * and ORM hydration apply (see `getSource` for why this matters —
1160
- * the pre-R3-D `getChildren` used raw `db.list`, which both bypassed
1161
- * tenant scoping and dropped camelCase property hydration; that
1162
- * latent breakage is fixed here).
1163
- *
1164
- * @returns Array of derivative Asset instances
1165
- */
1166
- async getDerivatives() {
1167
- if (!this.id) return [];
1168
- return await (await this._assetCollection()).list({ where: { sourceAssetId: this.id } });
1169
- }
1170
- /**
1171
- * Get the type of this asset
1172
- *
1173
- * @returns AssetType instance or null
1174
- */
1175
- async getType() {
1176
- if (!this.typeSlug) return null;
1177
- return await AssetType.getBySlug(this.typeSlug);
1178
- }
1179
- /**
1180
- * Get the status of this asset
1181
- *
1182
- * @returns AssetStatus instance or null
1183
- */
1184
- async getStatus() {
1185
- if (!this.statusSlug) return null;
1186
- return await AssetStatus.getBySlug(this.statusSlug);
1187
- }
1188
- /**
1189
- * Get all associations for this asset
1190
- *
1191
- * @returns Array of AssetAssociation instances
1192
- */
1193
- async getAssociations() {
1194
- return await (await AssetAssociationCollection.create({ db: this.db })).byRight(this.id);
1195
- }
1196
- /**
1197
- * Associate this asset with a target object
1198
- *
1199
- * @param metaType - Target class name or qualified name (e.g., 'Article' or '@pkg:Article')
1200
- * @param metaId - Target object ID
1201
- * @param role - Association role (default: 'default')
1202
- * @returns The created AssetAssociation
1203
- */
1204
- async associateWith(metaType, metaId, role = "default") {
1205
- return await (await AssetAssociationCollection.create({ db: this.db })).attach(metaType, metaId, this.id, { role });
1206
- }
1207
- /**
1208
- * Get asset by slug
1209
- *
1210
- * @param slug - The slug to search for
1211
- * @returns Asset instance or null
1212
- */
1213
- static async getBySlug(_slug) {
1214
- return null;
1215
- }
1216
- };
1217
- __publicField$4(Asset, "__smrtPackage__", "@happyvertical/smrt-assets");
1218
- __decorateClass$4([tenantId({ nullable: true })], Asset.prototype, "tenantId", 2);
1219
- __decorateClass$4([foreignKey("Asset")], Asset.prototype, "primaryVersionId", 2);
1220
- __decorateClass$4([crossPackageRef("@happyvertical/smrt-profiles:Profile")], Asset.prototype, "ownerProfileId", 2);
1221
- __decorateClass$4([foreignKey("Asset")], Asset.prototype, "sourceAssetId", 2);
1222
- __decorateClass$4([foreignKey("Folder")], Asset.prototype, "folderId", 2);
1223
- Asset = __decorateClass$4([TenantScoped({ mode: "optional" }), smrt({
1224
- tableStrategy: "sti",
1225
- api: { include: [
1226
- "list",
1227
- "get",
1228
- "create",
1229
- "update",
1230
- "delete"
1231
- ] },
1232
- mcp: { include: [
1233
- "list",
1234
- "get",
1235
- "create",
1236
- "update"
1237
- ] },
1238
- cli: { skipApiCheck: true }
1239
- })], Asset);
1240
- var __defProp$3 = Object.defineProperty;
1241
- var __getOwnPropDesc$3 = Object.getOwnPropertyDescriptor;
1242
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, {
1243
- enumerable: true,
1244
- configurable: true,
1245
- writable: true,
1246
- value
1247
- }) : obj[key] = value;
1248
- var __decorateClass$3 = (decorators, target, key, kind) => {
1249
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$3(target, key) : target;
1250
- for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
1251
- if (kind && result) __defProp$3(target, key, result);
1252
- return result;
1253
- };
1254
- var __publicField$3 = (obj, key, value) => __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
1255
- var AssetMetafield = class extends SmrtObject {
1256
- name = "";
1257
- validation = "";
1258
- constructor(options = {}) {
1259
- super(options);
1260
- if (options.slug) this.slug = options.slug;
1261
- if (options.name) this.name = options.name;
1262
- if (options.validation) this.validation = options.validation;
1263
- }
1264
- /**
1265
- * Get validation rules as parsed object
1266
- *
1267
- * @returns Parsed validation object or empty object if no validation
1268
- */
1269
- getValidation() {
1270
- if (!this.validation) return {};
1271
- try {
1272
- return JSON.parse(this.validation);
1273
- } catch {
1274
- return {};
1275
- }
1276
- }
1277
- /**
1278
- * Set validation rules from object
1279
- *
1280
- * @param rules - Validation rules object
1281
- */
1282
- setValidation(rules) {
1283
- this.validation = JSON.stringify(rules);
1284
- }
1285
- /**
1286
- * Get asset metafield by slug
1287
- *
1288
- * @param slug - The slug to search for
1289
- * @returns AssetMetafield instance or null
1290
- */
1291
- static async getBySlug(_slug) {
1292
- return null;
1293
- }
1294
- };
1295
- __publicField$3(AssetMetafield, "__smrtPackage__", "@happyvertical/smrt-assets");
1296
- AssetMetafield = __decorateClass$3([smrt({
1297
- tableStrategy: "sti",
1298
- api: { include: [
1299
- "list",
1300
- "get",
1301
- "create",
1302
- "update",
1303
- "delete"
1304
- ] },
1305
- mcp: { include: [
1306
- "list",
1307
- "get",
1308
- "create"
1309
- ] },
1310
- cli: { skipApiCheck: true }
1311
- })], AssetMetafield);
1312
- function assetTagSlug(label) {
1313
- return String(label ?? "").normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
1314
- }
1315
- function titleFromSlug(slug) {
1316
- const words = slug.replace(/-/g, " ");
1317
- return words.charAt(0).toUpperCase() + words.slice(1);
1318
- }
1319
- var AssetCollection = class extends SmrtCollection {
1320
- static _itemClass = Asset;
1321
- /**
1322
- * Find all assets belonging to a specific tenant
1323
- *
1324
- * @param tenantId - The tenant ID to filter by
1325
- * @returns Array of assets belonging to this tenant
1326
- */
1327
- async findByTenant(tenantId) {
1328
- return await this.list({ where: { tenantId } });
1329
- }
1330
- /**
1331
- * Find all global assets (assets without a tenant).
1332
- *
1333
- * Routes through the shared tenant-global helper so it does not throw under
1334
- * an active tenant context (an explicit `tenant_id IS NULL` filter would be
1335
- * flagged as an isolation violation). (#1600)
1336
- *
1337
- * @returns Array of global assets
1338
- */
1339
- async findGlobal() {
1340
- return queryGlobal(this);
1341
- }
1342
- /**
1343
- * Find assets belonging to a tenant plus all global assets.
1344
- *
1345
- * Fails closed if an active tenant context requests a different tenant's
1346
- * rows; the admin/system path keeps the cross-tenant capability. (#1600)
1347
- *
1348
- * @param tenantId - The tenant ID to include
1349
- * @returns Array of tenant-specific and global assets
1350
- */
1351
- async findWithGlobals(tenantId) {
1352
- return queryWithGlobals(this, tenantId, "Asset.findWithGlobals");
1353
- }
1354
- async assetTagCollection() {
1355
- const { AssetTagCollection } = await Promise.resolve().then(() => asset_tags_exports);
1356
- return AssetTagCollection.create({ db: this.db });
1357
- }
1358
- async tagCollection() {
1359
- return TagCollection.create({ db: this.db });
1360
- }
1361
- async requireAsset(assetId) {
1362
- const asset = await this.get({ id: assetId });
1363
- if (!asset?.id) throw new Error(`Asset '${assetId}' not found`);
1364
- return asset;
1365
- }
1366
- /**
1367
- * Find the asset's tag for `tag` (a slug or a label) in the asset's own
1368
- * tenant, optionally creating it. A tag of another tenant is never used.
1369
- */
1370
- async resolveAssetTag(asset, tag, options) {
1371
- const slug = assetTagSlug(tag);
1372
- if (!slug) throw new Error("A tag needs at least one letter or digit");
1373
- const context = options.context ?? "asset";
1374
- const tags = await this.tagCollection();
1375
- const existing = (await tags.list({
1376
- where: asset.tenantId ? {
1377
- slug,
1378
- context,
1379
- tenantId: asset.tenantId
1380
- } : {
1381
- slug,
1382
- context
1383
- },
1384
- limit: 10
1385
- })).find((candidate) => (candidate.tenantId ?? null) === (asset.tenantId ?? null));
1386
- if (existing || !options.create) return existing ?? null;
1387
- const trimmed = tag.trim();
1388
- return await tags.create({
1389
- slug,
1390
- name: options.name?.trim() || (trimmed !== slug ? trimmed : titleFromSlug(slug)),
1391
- context,
1392
- level: 0,
1393
- tenantId: asset.tenantId ?? null
1394
- });
1395
- }
1396
- /**
1397
- * Add a tag to an asset. `tag` is a slug (`town-hall`) or a label
1398
- * (`Town hall`); the tag is found or created in the asset's tenant under
1399
- * `context` (default {@link ASSET_TAG_CONTEXT}). Adding a tag twice is a
1400
- * no-op. Returns the Tag.
1401
- *
1402
- * @throws when the asset does not exist (or is not visible in the active
1403
- * tenant context)
1404
- */
1405
- async addTag(assetId, tag, options = {}) {
1406
- const asset = await this.requireAsset(assetId);
1407
- const resolved = await this.resolveAssetTag(asset, tag, {
1408
- ...options,
1409
- create: true
1410
- });
1411
- const links = await this.assetTagCollection();
1412
- if ((await links.byLeft(asset.id, { tagId: resolved.id })).length === 0) await links.attach(asset.id, resolved.id, { tenantId: asset.tenantId ?? null });
1413
- return resolved;
1414
- }
1415
- /**
1416
- * Remove a tag (slug or label) from an asset. Unknown tags are ignored.
1417
- * The Tag itself is kept; only the link goes.
1418
- */
1419
- async removeTag(assetId, tag, options = {}) {
1420
- const asset = await this.requireAsset(assetId);
1421
- const resolved = await this.resolveAssetTag(asset, tag, {
1422
- ...options,
1423
- create: false
1424
- });
1425
- if (!resolved?.id) return;
1426
- await (await this.assetTagCollection()).detach(asset.id, resolved.id);
1427
- }
1428
- /**
1429
- * Make the asset's tags (in `context`) exactly `tags`: missing ones are
1430
- * added, others in the same context removed. Returns the resulting Tags.
1431
- */
1432
- async setTags(assetId, tags, options = {}) {
1433
- const asset = await this.requireAsset(assetId);
1434
- const context = options.context ?? "asset";
1435
- const wanted = [];
1436
- const seen = /* @__PURE__ */ new Set();
1437
- for (const tag of tags) {
1438
- const slug = assetTagSlug(tag);
1439
- if (!slug || seen.has(slug)) continue;
1440
- seen.add(slug);
1441
- wanted.push(await this.addTag(asset.id, tag, { context }));
1442
- }
1443
- const wantedIds = new Set(wanted.map((tag) => tag.id));
1444
- const current = await asset.getTags();
1445
- for (const tag of current) if (tag.context === context && !wantedIds.has(tag.id)) await this.removeTag(asset.id, tag.slug, { context });
1446
- return wanted;
1447
- }
1448
- /**
1449
- * Tags for many assets in two queries, keyed by asset id (assets without
1450
- * tags map to an empty list). Useful for list views.
1451
- */
1452
- async getTagsForAssets(assetIds) {
1453
- const result = /* @__PURE__ */ new Map();
1454
- const ids = [...new Set(assetIds.filter(Boolean))];
1455
- for (const id of ids) result.set(id, []);
1456
- if (ids.length === 0) return result;
1457
- const rows = await (await this.assetTagCollection()).list({ where: { "assetId in": ids } });
1458
- if (rows.length === 0) return result;
1459
- const tags = await this.tagCollection();
1460
- const tagById = new Map((await tags.listByIds([...new Set(rows.map((row) => row.tagId))])).filter((tag) => tag.id).map((tag) => [tag.id, tag]));
1461
- for (const row of rows) {
1462
- const tag = tagById.get(row.tagId);
1463
- if (tag) result.get(row.assetId)?.push(tag);
1464
- }
1465
- for (const list of result.values()) list.sort((a, b) => a.name.localeCompare(b.name));
1466
- return result;
1467
- }
1468
- /**
1469
- * Get all assets with a specific tag (slug or label), within the active
1470
- * tenant context.
1471
- */
1472
- async getByTag(tag, options = {}) {
1473
- const slug = assetTagSlug(tag);
1474
- if (!slug) return [];
1475
- const tagIds = (await (await this.tagCollection()).list({ where: {
1476
- slug,
1477
- context: options.context ?? "asset"
1478
- } })).map((match) => match.id).filter(Boolean);
1479
- if (tagIds.length === 0) return [];
1480
- const rows = await (await this.assetTagCollection()).list({ where: { "tagId in": tagIds } });
1481
- const assetIds = [...new Set(rows.map((row) => row.assetId))];
1482
- if (assetIds.length === 0) return [];
1483
- return await this.listByIds(assetIds);
1484
- }
1485
- /**
1486
- * Get assets by type
1487
- *
1488
- * @param typeSlug - The asset type slug (e.g., 'image', 'video')
1489
- * @returns Array of assets matching the type
1490
- */
1491
- async getByType(typeSlug) {
1492
- return await this.list({ where: { typeSlug } });
1493
- }
1494
- /**
1495
- * Get assets by status
1496
- *
1497
- * @param statusSlug - The asset status slug (e.g., 'published', 'draft')
1498
- * @returns Array of assets matching the status
1499
- */
1500
- async getByStatus(statusSlug) {
1501
- return await this.list({ where: { statusSlug } });
1502
- }
1503
- /**
1504
- * Get assets by owner
1505
- *
1506
- * @param ownerProfileId - The profile ID of the owner
1507
- * @returns Array of assets owned by this profile
1508
- */
1509
- async getByOwner(ownerProfileId) {
1510
- return await this.list({ where: { ownerProfileId } });
1511
- }
1512
- /**
1513
- * Create a new version of an existing asset
1514
- *
1515
- * @param primaryVersionId - The primary version ID (first version's ID)
1516
- * @param newSourceUri - The new source URI for this version
1517
- * @param updates - Optional additional updates
1518
- * @returns The newly created asset version
1519
- */
1520
- async createNewVersion(primaryVersionId, newSourceUri, updates = {}) {
1521
- const versions = await this.listVersions(primaryVersionId);
1522
- if (versions.length === 0) throw new Error(`No asset found with primary version ID: ${primaryVersionId}`);
1523
- versions.sort((a, b) => b.version - a.version);
1524
- const latestVersion = versions[0];
1525
- const newVersionNumber = latestVersion.version + 1;
1526
- const primary = versions.find((v) => v.id === primaryVersionId) ?? versions[versions.length - 1];
1527
- const baseSlug = String(primary?.slug ?? "") || "asset";
1528
- const takenInChain = new Set(versions.map((v) => v.slug).filter(Boolean));
1529
- let candidate = `${baseSlug}-v${newVersionNumber}`;
1530
- for (let attempt = 1;; attempt += 1) {
1531
- if (!(takenInChain.has(candidate) || await this.get({ slug: candidate }) !== null)) break;
1532
- candidate = `${baseSlug}-v${newVersionNumber}-${attempt}`;
1533
- }
1534
- return await this.create({
1535
- ...latestVersion,
1536
- id: void 0,
1537
- slug: candidate,
1538
- sourceUri: newSourceUri,
1539
- version: newVersionNumber,
1540
- primaryVersionId,
1541
- createdAt: /* @__PURE__ */ new Date(),
1542
- updatedAt: /* @__PURE__ */ new Date(),
1543
- ...updates
1544
- });
1545
- }
1546
- /**
1547
- * Get the latest version of an asset
1548
- *
1549
- * @param primaryVersionId - The primary version ID
1550
- * @returns The latest version or null
1551
- */
1552
- async getLatestVersion(primaryVersionId) {
1553
- const versions = await this.listVersions(primaryVersionId);
1554
- if (versions.length === 0) return null;
1555
- versions.sort((a, b) => b.version - a.version);
1556
- return versions[0];
1557
- }
1558
- /**
1559
- * List all versions of an asset
1560
- *
1561
- * @param primaryVersionId - The primary version ID
1562
- * @returns Array of all asset versions, ordered by version number
1563
- */
1564
- async listVersions(primaryVersionId) {
1565
- const [chained, primary] = await Promise.all([this.list({ where: { primaryVersionId } }), this.get({ id: primaryVersionId })]);
1566
- const byId = /* @__PURE__ */ new Map();
1567
- for (const asset of [...primary ? [primary] : [], ...chained]) if (asset?.id) byId.set(asset.id, asset);
1568
- const assets = Array.from(byId.values());
1569
- assets.sort((a, b) => a.version - b.version);
1570
- return assets;
1571
- }
1572
- /**
1573
- * Get derivative assets of a source asset.
1574
- *
1575
- * Renamed from `getChildren(parentId)` in R3-D to match the rename of
1576
- * the underlying column (`parent_id` → `source_asset_id`) and method
1577
- * (`Asset.getChildren` → `Asset.getDerivatives`).
1578
- *
1579
- * @param sourceAssetId - The source asset ID
1580
- * @returns Array of derivative assets
1581
- */
1582
- async getDerivatives(sourceAssetId) {
1583
- return await this.list({ where: { sourceAssetId } });
1584
- }
1585
- /**
1586
- * Get assets by MIME type pattern
1587
- *
1588
- * @param mimePattern - MIME type pattern (e.g., 'image/*', 'video/mp4')
1589
- * @returns Array of matching assets
1590
- */
1591
- async getByMimeType(mimePattern) {
1592
- const pattern = mimePattern.replace("*", "%");
1593
- return await this.list({ where: { "mimeType like": pattern } });
1594
- }
1595
- /**
1596
- * Rollback to a previous version by creating a new version with the target's content.
1597
- * Does NOT delete intermediate versions (safe rollback).
1598
- *
1599
- * @param primaryVersionId - The primary version ID of the version chain
1600
- * @param targetVersion - The version number to rollback to
1601
- * @returns The newly created asset version with content copied from target
1602
- */
1603
- async rollbackToVersion(primaryVersionId, targetVersion) {
1604
- const target = (await this.listVersions(primaryVersionId)).find((v) => v.version === targetVersion);
1605
- if (!target) throw new Error(`Version ${targetVersion} not found for asset ${primaryVersionId}`);
1606
- return await this.createNewVersion(primaryVersionId, target.sourceUri, { description: `Rollback to version ${targetVersion}` });
1607
- }
1608
- /**
1609
- * Get assets in a specific folder
1610
- *
1611
- * @param folderId - The folder ID to list contents for
1612
- * @returns Array of assets in this folder
1613
- */
1614
- async getByFolder(folderId) {
1615
- return await this.list({ where: { folderId } });
1616
- }
1617
- };
1618
- var __defProp$2 = Object.defineProperty;
1619
- var __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor;
1620
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, {
1621
- enumerable: true,
1622
- configurable: true,
1623
- writable: true,
1624
- value
1625
- }) : obj[key] = value;
1626
- var __decorateClass$2 = (decorators, target, key, kind) => {
1627
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$2(target, key) : target;
1628
- for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
1629
- if (kind && result) __defProp$2(target, key, result);
1630
- return result;
1631
- };
1632
- var __publicField$2 = (obj, key, value) => __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
1633
- var AssetTag = class extends SmrtObject {
1634
- tenantId = null;
1635
- assetId = "";
1636
- tagId = "";
1637
- constructor(options = {}) {
1638
- super(options);
1639
- if (options.assetId) this.assetId = options.assetId;
1640
- if (options.tagId) this.tagId = options.tagId;
1641
- if (options.tenantId !== void 0) this.tenantId = options.tenantId;
1642
- }
1643
- };
1644
- __publicField$2(AssetTag, "__smrtPackage__", "@happyvertical/smrt-assets");
1645
- __decorateClass$2([tenantId({ nullable: true })], AssetTag.prototype, "tenantId", 2);
1646
- __decorateClass$2([foreignKey("Asset", {
1647
- required: true,
1648
- onDelete: "CASCADE"
1649
- })], AssetTag.prototype, "assetId", 2);
1650
- __decorateClass$2([crossPackageRef("@happyvertical/smrt-tags:Tag", {
1651
- required: true,
1652
- onDelete: "CASCADE"
1653
- })], AssetTag.prototype, "tagId", 2);
1654
- AssetTag = __decorateClass$2([TenantScoped({ mode: "optional" }), smrt({
1655
- tableName: "asset_tags",
1656
- conflictColumns: ["asset_id", "tag_id"],
1657
- api: false,
1658
- mcp: false,
1659
- cli: false
1660
- })], AssetTag);
1661
- var asset_tags_exports = /* @__PURE__ */ __exportAll({ AssetTagCollection: () => AssetTagCollection });
1662
- var __defProp$1 = Object.defineProperty;
1663
- var __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor;
1664
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, {
1665
- enumerable: true,
1666
- configurable: true,
1667
- writable: true,
1668
- value
1669
- }) : obj[key] = value;
1670
- var __decorateClass$1 = (decorators, target, key, kind) => {
1671
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$1(target, key) : target;
1672
- for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
1673
- if (kind && result) __defProp$1(target, key, result);
1674
- return result;
1675
- };
1676
- var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
1677
- var AssetTagCollection = class extends SmrtJunction {
1678
- leftField = "assetId";
1679
- rightField = "tagId";
1680
- sortField = null;
1681
- positionField = null;
1682
- };
1683
- __publicField$1(AssetTagCollection, "__smrtPackage__", "@happyvertical/smrt-assets");
1684
- __publicField$1(AssetTagCollection, "_itemClass", AssetTag);
1685
- AssetTagCollection = __decorateClass$1([smrt()], AssetTagCollection);
1686
- var __defProp = Object.defineProperty;
1687
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1688
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
1689
- enumerable: true,
1690
- configurable: true,
1691
- writable: true,
1692
- value
1693
- }) : obj[key] = value;
1694
- var __decorateClass = (decorators, target, key, kind) => {
1695
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
1696
- for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
1697
- if (kind && result) __defProp(target, key, result);
1698
- return result;
1699
- };
1700
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
1701
- var Folder = class extends SmrtHierarchical {
1702
- tenantId = null;
1703
- name = "";
1704
- description = "";
1705
- ownerProfileId = null;
1706
- createdAt = /* @__PURE__ */ new Date();
1707
- updatedAt = /* @__PURE__ */ new Date();
1708
- constructor(options = {}) {
1709
- super(options);
1710
- if (options.name !== void 0) this.name = options.name;
1711
- if (options.slug !== void 0) this.slug = options.slug;
1712
- if (options.description !== void 0) this.description = options.description;
1713
- if (options.parentId !== void 0) this.parentId = options.parentId ?? null;
1714
- if (options.ownerProfileId !== void 0) this.ownerProfileId = options.ownerProfileId;
1715
- if (options.tenantId !== void 0) this.tenantId = options.tenantId;
1716
- if (options.createdAt) this.createdAt = options.createdAt;
1717
- if (options.updatedAt) this.updatedAt = options.updatedAt;
1718
- }
1719
- /**
1720
- * Look up a folder by slug.
1721
- */
1722
- static async getBySlug(_slug) {
1723
- return null;
1724
- }
1725
- };
1726
- __publicField(Folder, "__smrtPackage__", "@happyvertical/smrt-assets");
1727
- __decorateClass([tenantId({ nullable: true })], Folder.prototype, "tenantId", 2);
1728
- __decorateClass([crossPackageRef("@happyvertical/smrt-profiles:Profile")], Folder.prototype, "ownerProfileId", 2);
1729
- Folder = __decorateClass([TenantScoped({ mode: "optional" }), smrt({
1730
- api: { include: [
1731
- "list",
1732
- "get",
1733
- "create",
1734
- "update",
1735
- "delete"
1736
- ] },
1737
- mcp: { include: [
1738
- "list",
1739
- "get",
1740
- "create",
1741
- "update"
1742
- ] },
1743
- cli: { skipApiCheck: true }
1744
- })], Folder);
1745
- var OWNED_ASSET_RELATIONSHIP_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
1746
- function assertValidOwnedAssetRelationship(relationship) {
1747
- if (!OWNED_ASSET_RELATIONSHIP_PATTERN.test(relationship)) throw new Error(`Invalid relationship type "${relationship}"; must start with a letter or underscore and contain only letters, digits, and underscores`);
1748
- }
1749
- function assertValidOwnedAssetSortOrder(sortOrder) {
1750
- if (!Number.isInteger(sortOrder) || sortOrder < 0 || sortOrder > 2147483647) throw new Error(`Invalid sortOrder "${sortOrder}"; must be a non-negative integer`);
1751
- }
1752
- async function assertAssetLinkable(db, assetId, ownerTenantId, ownerLabel) {
1753
- const assets = await AssetCollection.create({ db });
1754
- const [stored] = await withSystemContext(async () => assets.listByIds([assetId]));
1755
- if (!stored) throw new Error(`Cannot associate asset ${assetId}: it does not exist`);
1756
- const assetTenant = stored.tenantId ? String(stored.tenantId) : null;
1757
- const ownerTenant = ownerTenantId ? String(ownerTenantId) : null;
1758
- if (assetTenant === null || assetTenant === ownerTenant) return;
1759
- throw new Error(ownerTenant === null ? `Cannot associate a tenant's asset with a shared ${ownerLabel}` : `Cannot associate an asset from another tenant with this ${ownerLabel}`);
1760
- }
1761
- async function resolveOwnedAssetsById(db, assetIds, tenantId) {
1762
- if (assetIds.length === 0) return [];
1763
- const assets = await AssetCollection.create({ db });
1764
- const resolved = tenantId ? await withSystemContext(async () => assets.listByIds(assetIds)) : await assets.listByIds(assetIds);
1765
- const visibleAssets = tenantId ? resolved.filter((asset) => asset.tenantId === tenantId || asset.tenantId === null) : resolved;
1766
- const assetsById = new Map(visibleAssets.filter((asset) => asset.id).map((asset) => [asset.id, asset]));
1767
- return assetIds.map((assetId) => assetsById.get(assetId)).filter(Boolean);
1768
- }
1769
- async function getOwnerRecord(collection, ownerId) {
1770
- return collection.get({ id: ownerId });
1771
- }
1772
- async function getOwnedAssetsFromCollection(collection, ownerId, relationship) {
1773
- const owner = await getOwnerRecord(collection, ownerId);
1774
- if (!owner) return [];
1775
- return owner.getAssets(relationship);
1776
- }
1777
- async function addOwnedAssetFromCollection(collection, ownerType, ownerId, asset, relationship = "attachment", sortOrder = 0) {
1778
- const owner = await getOwnerRecord(collection, ownerId);
1779
- if (!owner) throw new Error(`${ownerType} '${ownerId}' not found`);
1780
- await owner.addAsset(asset, relationship, sortOrder);
1781
- }
1782
- async function removeOwnedAssetFromCollection(collection, ownerType, ownerId, assetId, relationship) {
1783
- const owner = await getOwnerRecord(collection, ownerId);
1784
- if (!owner) throw new Error(`${ownerType} '${ownerId}' not found`);
1785
- await owner.removeAsset(assetId, relationship);
1786
- }
1787
- //#endregion
1788
- export { getOwnedAssetsFromCollection as a, assertValidOwnedAssetSortOrder as i, assertAssetLinkable as n, removeOwnedAssetFromCollection as o, assertValidOwnedAssetRelationship as r, resolveOwnedAssetsById as s, addOwnedAssetFromCollection as t };