@origen-ui/admin-cli 1.0.2 → 1.1.0

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 (163) hide show
  1. package/package.json +3 -3
  2. package/templates/current/clean/CHANGELOG.md +53 -0
  3. package/templates/current/clean/component-catalog.json +9 -9
  4. package/templates/current/clean/package.json +41 -41
  5. package/templates/current/clean/scaffold.lock.json +2 -2
  6. package/templates/current/clean/scripts/vite-build-policy.spec.ts +71 -0
  7. package/templates/current/clean/src/App.vue +10 -3
  8. package/templates/current/clean/src/api/client.ts +90 -10
  9. package/templates/current/clean/src/api/generated/data-contracts.ts +268 -0
  10. package/templates/current/clean/src/api/generated/http-client.ts +266 -0
  11. package/templates/current/clean/src/api/generated//347/263/273/347/273/237/347/256/241/347/220/206/345/206/205/345/256/271/346/226/207/347/253/240.ts +147 -0
  12. package/templates/current/clean/src/api/generated//347/263/273/347/273/237/347/256/241/347/220/206/345/256/241/350/256/241.ts +53 -0
  13. package/templates/current/clean/src/api/generated//347/263/273/347/273/237/347/256/241/347/220/206/346/226/207/344/273/266/344/270/212/344/274/240.ts +66 -0
  14. package/templates/current/clean/src/api/generated//347/263/273/347/273/237/347/256/241/347/220/206/347/224/250/346/210/267.ts +171 -0
  15. package/templates/current/clean/src/api/generated//347/263/273/347/273/237/347/256/241/347/220/206/350/217/234/345/215/225.ts +181 -0
  16. package/templates/current/clean/src/api/generated//347/263/273/347/273/237/347/256/241/347/220/206/350/247/222/350/211/262.ts +169 -0
  17. package/templates/current/clean/src/api/generated//347/263/273/347/273/237/347/256/241/347/220/206/350/256/242/345/215/225/350/215/211/347/250/277.ts +170 -0
  18. package/templates/current/clean/src/api/generated//350/256/244/350/257/201.ts +98 -0
  19. package/templates/current/clean/src/app/adminLocale.ts +90 -0
  20. package/templates/current/clean/src/app/createAdminUi.spec.ts +65 -9
  21. package/templates/current/clean/src/app/createAdminUi.ts +14 -29
  22. package/templates/current/clean/src/app/embedded-token.spec.ts +40 -0
  23. package/templates/current/clean/src/app/embedded.spec.ts +135 -0
  24. package/templates/current/clean/src/app/embedded.ts +255 -0
  25. package/templates/current/clean/src/app/localeFormat.ts +52 -0
  26. package/templates/current/clean/src/app/menu.spec.ts +26 -0
  27. package/templates/current/clean/src/app/menu.ts +4 -0
  28. package/templates/current/clean/src/app/menuTypes.ts +1 -0
  29. package/templates/current/clean/src/app/origenUiLocale.spec.ts +6 -5
  30. package/templates/current/clean/src/app/origenUiLocale.ts +3 -58
  31. package/templates/current/clean/src/app/permission.spec.ts +26 -0
  32. package/templates/current/clean/src/app/runtimeConfig.ts +8 -7
  33. package/templates/current/clean/src/env.d.ts +18 -0
  34. package/templates/current/clean/src/features/appearance/components/ThemePanel.vue +21 -17
  35. package/templates/current/clean/src/features/appearance/store/theme.ts +2 -1
  36. package/templates/current/clean/src/features/auth/pages/Login.vue +15 -11
  37. package/templates/current/clean/src/features/auth/store/auth.ts +13 -3
  38. package/templates/current/clean/src/features/security/components/DevtoolsProtectionOverlay.vue +5 -2
  39. package/templates/current/clean/src/features/security/devtoolsProtection.spec.ts +7 -10
  40. package/templates/current/clean/src/features/security/devtoolsProtection.ts +2 -1
  41. package/templates/current/clean/src/features/system/access/api/admin-repository.spec.ts +14 -0
  42. package/templates/current/clean/src/features/system/access/api/admin-repository.ts +38 -15
  43. package/templates/current/clean/src/features/system/access/api/rbac.ts +37 -27
  44. package/templates/current/clean/src/features/workspace/pages/Empty.vue +4 -1
  45. package/templates/current/clean/src/features/workspace/pages/Profile.vue +13 -11
  46. package/templates/current/clean/src/layouts/AdminLayout.vue +3 -1
  47. package/templates/current/clean/src/layouts/TopBar.vue +26 -8
  48. package/templates/current/clean/src/locales/en-US.json +490 -0
  49. package/templates/current/clean/src/locales/en-US.runtime.ts +20 -0
  50. package/templates/current/clean/src/locales/index.ts +129 -45
  51. package/templates/current/clean/src/locales/messages-types.ts +62 -0
  52. package/templates/current/clean/src/locales/messages.spec.ts +113 -6
  53. package/templates/current/clean/src/locales/vue-i18n.d.ts +5 -0
  54. package/templates/current/clean/src/locales/zh-CN.json +490 -0
  55. package/templates/current/clean/src/locales/zh-CN.runtime.ts +20 -0
  56. package/templates/current/clean/src/locales/zh-TW.json +490 -0
  57. package/templates/current/clean/src/locales/zh-TW.runtime.ts +20 -0
  58. package/templates/current/clean/src/router/bootstrap.ts +22 -7
  59. package/templates/current/clean/src/router/dynamicRoutes.ts +5 -1
  60. package/templates/current/clean/src/router/queryEncryption.spec.ts +30 -4
  61. package/templates/current/clean/src/router/queryEncryption.ts +48 -44
  62. package/templates/current/clean/src/router/useRouteQueryDefaults.spec.ts +2 -1
  63. package/templates/current/clean/src/router/useRouteQueryDefaults.types.ts +2 -1
  64. package/templates/current/clean/src/templates/og-table.ts +81 -37
  65. package/templates/current/clean/src/templates/templates.spec.ts +19 -0
  66. package/templates/current/clean/vite.build-policy.ts +114 -289
  67. package/templates/current/clean/vite.config.ts +4 -5
  68. package/templates/current/examples/CHANGELOG.md +53 -0
  69. package/templates/current/examples/component-catalog.json +9 -9
  70. package/templates/current/examples/package.json +41 -41
  71. package/templates/current/examples/scaffold.lock.json +2 -2
  72. package/templates/current/examples/scripts/vite-build-policy.spec.ts +71 -0
  73. package/templates/current/examples/src/App.vue +10 -3
  74. package/templates/current/examples/src/api/client.ts +90 -10
  75. package/templates/current/examples/src/api/generated/data-contracts.ts +268 -0
  76. package/templates/current/examples/src/api/generated/http-client.ts +266 -0
  77. package/templates/current/examples/src/api/generated//347/263/273/347/273/237/347/256/241/347/220/206/345/206/205/345/256/271/346/226/207/347/253/240.ts +147 -0
  78. package/templates/current/examples/src/api/generated//347/263/273/347/273/237/347/256/241/347/220/206/345/256/241/350/256/241.ts +53 -0
  79. package/templates/current/examples/src/api/generated//347/263/273/347/273/237/347/256/241/347/220/206/346/226/207/344/273/266/344/270/212/344/274/240.ts +66 -0
  80. package/templates/current/examples/src/api/generated//347/263/273/347/273/237/347/256/241/347/220/206/347/224/250/346/210/267.ts +171 -0
  81. package/templates/current/examples/src/api/generated//347/263/273/347/273/237/347/256/241/347/220/206/350/217/234/345/215/225.ts +181 -0
  82. package/templates/current/examples/src/api/generated//347/263/273/347/273/237/347/256/241/347/220/206/350/247/222/350/211/262.ts +169 -0
  83. package/templates/current/examples/src/api/generated//347/263/273/347/273/237/347/256/241/347/220/206/350/256/242/345/215/225/350/215/211/347/250/277.ts +170 -0
  84. package/templates/current/examples/src/api/generated//350/256/244/350/257/201.ts +98 -0
  85. package/templates/current/examples/src/app/adminLocale.ts +90 -0
  86. package/templates/current/examples/src/app/createAdminUi.spec.ts +65 -9
  87. package/templates/current/examples/src/app/createAdminUi.ts +14 -29
  88. package/templates/current/examples/src/app/embedded-token.spec.ts +40 -0
  89. package/templates/current/examples/src/app/embedded.spec.ts +135 -0
  90. package/templates/current/examples/src/app/embedded.ts +255 -0
  91. package/templates/current/examples/src/app/localeFormat.ts +52 -0
  92. package/templates/current/examples/src/app/menu.spec.ts +26 -0
  93. package/templates/current/examples/src/app/menu.ts +4 -0
  94. package/templates/current/examples/src/app/menuTypes.ts +1 -0
  95. package/templates/current/examples/src/app/origenUiLocale.spec.ts +6 -5
  96. package/templates/current/examples/src/app/origenUiLocale.ts +3 -58
  97. package/templates/current/examples/src/app/permission.spec.ts +26 -0
  98. package/templates/current/examples/src/app/runtimeConfig.ts +8 -7
  99. package/templates/current/examples/src/env.d.ts +18 -0
  100. package/templates/current/examples/src/features/appearance/components/ThemePanel.vue +21 -17
  101. package/templates/current/examples/src/features/appearance/store/theme.ts +2 -1
  102. package/templates/current/examples/src/features/auth/pages/Login.vue +15 -11
  103. package/templates/current/examples/src/features/auth/store/auth.ts +13 -3
  104. package/templates/current/examples/src/features/errors/pages/Forbidden.vue +6 -2
  105. package/templates/current/examples/src/features/errors/pages/NotFound.vue +6 -2
  106. package/templates/current/examples/src/features/errors/pages/ServerError.vue +6 -2
  107. package/templates/current/examples/src/features/errors/pages/error-pages.spec.ts +9 -1
  108. package/templates/current/examples/src/features/feature-composables.spec.ts +36 -9
  109. package/templates/current/examples/src/features/security/components/DevtoolsProtectionOverlay.vue +5 -2
  110. package/templates/current/examples/src/features/security/devtoolsProtection.spec.ts +7 -10
  111. package/templates/current/examples/src/features/security/devtoolsProtection.ts +2 -1
  112. package/templates/current/examples/src/features/system/access/api/admin-repository.spec.ts +14 -0
  113. package/templates/current/examples/src/features/system/access/api/admin-repository.ts +38 -15
  114. package/templates/current/examples/src/features/system/access/api/rbac.ts +37 -27
  115. package/templates/current/examples/src/features/system/audit/composables/useAuditManagement.ts +43 -38
  116. package/templates/current/examples/src/features/system/menus/components/MenuEditorForm.vue +33 -30
  117. package/templates/current/examples/src/features/system/menus/composables/useMenuManagement.ts +81 -69
  118. package/templates/current/examples/src/features/system/menus/pages/MenuList.vue +3 -1
  119. package/templates/current/examples/src/features/system/roles/components/RoleEditorForm.vue +18 -15
  120. package/templates/current/examples/src/features/system/roles/composables/useRoleManagement.ts +49 -53
  121. package/templates/current/examples/src/features/system/roles/pages/RoleList.vue +3 -1
  122. package/templates/current/examples/src/features/system/users/components/UserEditorForm.vue +22 -19
  123. package/templates/current/examples/src/features/system/users/composables/useUserManagement.ts +59 -64
  124. package/templates/current/examples/src/features/system/users/pages/UserList.vue +3 -1
  125. package/templates/current/examples/src/features/workspace/pages/Dashboard.spec.ts +9 -0
  126. package/templates/current/examples/src/features/workspace/pages/Dashboard.vue +54 -26
  127. package/templates/current/examples/src/features/workspace/pages/Empty.vue +4 -1
  128. package/templates/current/examples/src/features/workspace/pages/Profile.vue +13 -11
  129. package/templates/current/examples/src/layouts/AdminLayout.vue +3 -1
  130. package/templates/current/examples/src/layouts/TopBar.vue +26 -8
  131. package/templates/current/examples/src/locales/en-US.json +490 -0
  132. package/templates/current/examples/src/locales/en-US.runtime.ts +20 -0
  133. package/templates/current/examples/src/locales/index.ts +129 -45
  134. package/templates/current/examples/src/locales/messages-types.ts +62 -0
  135. package/templates/current/examples/src/locales/messages.spec.ts +113 -6
  136. package/templates/current/examples/src/locales/vue-i18n.d.ts +5 -0
  137. package/templates/current/examples/src/locales/zh-CN.json +490 -0
  138. package/templates/current/examples/src/locales/zh-CN.runtime.ts +20 -0
  139. package/templates/current/examples/src/locales/zh-TW.json +490 -0
  140. package/templates/current/examples/src/locales/zh-TW.runtime.ts +20 -0
  141. package/templates/current/examples/src/main.ts +31 -5
  142. package/templates/current/examples/src/router/bootstrap.ts +22 -7
  143. package/templates/current/examples/src/router/dynamicRoutes.spec.ts +17 -0
  144. package/templates/current/examples/src/router/dynamicRoutes.ts +5 -1
  145. package/templates/current/examples/src/router/queryEncryption.spec.ts +30 -4
  146. package/templates/current/examples/src/router/queryEncryption.ts +48 -44
  147. package/templates/current/examples/src/router/staticRoutes.ts +1 -1
  148. package/templates/current/examples/src/router/useRouteQueryDefaults.spec.ts +2 -1
  149. package/templates/current/examples/src/router/useRouteQueryDefaults.types.ts +2 -1
  150. package/templates/current/examples/src/templates/og-table.ts +81 -37
  151. package/templates/current/examples/src/templates/templates.spec.ts +19 -0
  152. package/templates/current/examples/vite.build-policy.ts +114 -289
  153. package/templates/current/examples/vite.config.ts +4 -5
  154. package/templates/current/clean/scripts/check-admin-bundle.mjs +0 -214
  155. package/templates/current/clean/scripts/performance/baselines/bundle-gzip-v2-pre-entry-unification.json +0 -38
  156. package/templates/current/clean/src/locales/en-US.ts +0 -55
  157. package/templates/current/clean/src/locales/zh-CN.ts +0 -55
  158. package/templates/current/clean/src/locales/zh-TW.ts +0 -44
  159. package/templates/current/examples/scripts/check-admin-bundle.mjs +0 -214
  160. package/templates/current/examples/scripts/performance/baselines/bundle-gzip-v2-pre-entry-unification.json +0 -38
  161. package/templates/current/examples/src/locales/en-US.ts +0 -55
  162. package/templates/current/examples/src/locales/zh-CN.ts +0 -55
  163. package/templates/current/examples/src/locales/zh-TW.ts +0 -44
@@ -1,4 +1,7 @@
1
+ import type { OrigenUiMessages } from 'origen-ui'
2
+ import type { OrigenUiLanguageRuntime } from 'origen-ui/language'
1
3
  import type { App, Plugin } from 'vue'
4
+ import { createOrigenUiLanguageRuntime } from 'origen-ui/language'
2
5
  import { beforeEach, describe, expect, it, vi } from 'vitest'
3
6
 
4
7
  import { createAdminUi } from './createAdminUi'
@@ -73,19 +76,15 @@ describe('createAdminUi', () => {
73
76
 
74
77
  plugin.install?.(app)
75
78
 
76
- expect(dependencies.createOgDialog).toHaveBeenCalledWith(
77
- expect.objectContaining({ locale: expect.any(Object) }),
78
- )
79
+ expect(dependencies.createOgDialog).toHaveBeenCalledOnce()
79
80
  expect(dependencies.createOgForm).toHaveBeenCalledWith(
80
81
  expect.objectContaining({
81
- locale: expect.any(Object),
82
82
  permissions: { has: dependencies.permission },
83
83
  size: 'default',
84
84
  }),
85
85
  )
86
86
  expect(dependencies.createOgSearch).toHaveBeenCalledWith(
87
87
  expect.objectContaining({
88
- config: expect.objectContaining({ locale: expect.any(Object) }),
89
88
  permissions: { has: dependencies.permission },
90
89
  size: 'default',
91
90
  }),
@@ -93,18 +92,75 @@ describe('createAdminUi', () => {
93
92
  expect(dependencies.createOgTable).toHaveBeenCalledWith(
94
93
  expect.objectContaining({
95
94
  config: expect.objectContaining({
96
- locale: expect.any(Object),
97
95
  permissions: { has: dependencies.permission },
98
96
  }),
99
97
  }),
100
98
  )
101
- expect(dependencies.createOgTabs).toHaveBeenCalledWith(
102
- expect.objectContaining({ locale: expect.any(Object) }),
103
- )
99
+ expect(dependencies.createOgTabs).toHaveBeenCalledOnce()
104
100
  expect(app.use).toHaveBeenCalledWith(dependencies.createOgDialog.mock.results[0]?.value)
105
101
  expect(app.use).toHaveBeenCalledWith(dependencies.createOgForm.mock.results[0]?.value)
106
102
  expect(app.use).toHaveBeenCalledWith(dependencies.createOgSearch.mock.results[0]?.value)
107
103
  expect(app.use).toHaveBeenCalledWith(dependencies.createOgTable.mock.results[0]?.value)
108
104
  expect(app.use).toHaveBeenCalledWith(dependencies.createOgTabs.mock.results[0]?.value)
109
105
  })
106
+
107
+ it('never installs a static full locale bundle that could shadow language switches', () => {
108
+ const language = createOrigenUiLanguageRuntime<
109
+ Record<string, unknown>,
110
+ unknown,
111
+ OrigenUiMessages
112
+ >()
113
+ createAdminUi(language)
114
+
115
+ const dialogOptions = dependencies.createOgDialog.mock.calls[0]?.[0] as {
116
+ locale?: unknown
117
+ localeSource?: { value?: { confirmText?: string } }
118
+ }
119
+ expect(dialogOptions.locale).toBeUndefined()
120
+ expect(dialogOptions.localeSource).toBeDefined()
121
+ })
122
+
123
+ it('lets component copy follow the language runtime after a switch', async () => {
124
+ const language: OrigenUiLanguageRuntime<
125
+ Record<string, unknown>,
126
+ unknown,
127
+ OrigenUiMessages
128
+ > = createOrigenUiLanguageRuntime({
129
+ initial: 'zh-CN',
130
+ loaders: {
131
+ 'zh-CN': async () => {
132
+ const [{ default: messages }, { elementPlus, origenUi }] = await Promise.all([
133
+ import('../locales/zh-CN.json'),
134
+ import('../locales/zh-CN.runtime'),
135
+ ])
136
+ return { locale: 'zh-CN', messages, elementPlus, origenUi }
137
+ },
138
+ 'en-US': async () => {
139
+ const [{ default: messages }, { elementPlus, origenUi }] = await Promise.all([
140
+ import('../locales/en-US.json'),
141
+ import('../locales/en-US.runtime'),
142
+ ])
143
+ return { locale: 'en-US', messages, elementPlus, origenUi }
144
+ },
145
+ },
146
+ })
147
+ await language.ready
148
+
149
+ createAdminUi(language)
150
+
151
+ const dialogOptions = dependencies.createOgDialog.mock.calls[0]?.[0] as {
152
+ localeSource?: { value?: { confirmText?: string } }
153
+ }
154
+ const tableOptions = dependencies.createOgTable.mock.calls[0]?.[0] as {
155
+ localeSource?: { value?: { refresh?: string } }
156
+ }
157
+ expect(dialogOptions.localeSource?.value?.confirmText).toBe('确定')
158
+ expect(tableOptions.localeSource?.value?.refresh).toBe('刷新')
159
+ expect(language.current.value).toBe('zh-CN')
160
+
161
+ await language.setLocale('en-US')
162
+
163
+ expect(dialogOptions.localeSource?.value?.confirmText).toBe('Confirm')
164
+ expect(tableOptions.localeSource?.value?.refresh).toBe('Refresh')
165
+ })
110
166
  })
@@ -10,59 +10,44 @@ import { computed } from 'vue'
10
10
  import { permission } from './permission'
11
11
  import { appRuntimeConfig } from './runtimeConfig'
12
12
 
13
- function mergeLocale<T extends object>(shared: T | undefined, local: T | undefined): T | undefined {
14
- if (!shared && !local) return undefined
15
- return { ...shared, ...local } as T
16
- }
17
-
18
13
  /** Installs only the UI runtimes used by the Admin application. */
19
14
  export function createAdminUi(
20
15
  language?: OrigenUiLanguageRuntime<Record<string, unknown>, unknown, OrigenUiMessages>,
21
16
  ): Plugin {
22
17
  const origenUi = appRuntimeConfig.origenUi
23
- const dialogOptions = origenUi.dialog
24
- const formOptions = origenUi.form
25
- const searchOptions = origenUi.search
26
- const tableOptions = origenUi.table
27
- const tabsOptions = origenUi.tabs
28
18
  const locale = language?.origenUi
19
+ // Component copy follows the reactive language runtime; static configuration
20
+ // may only carry explicit overrides, never a full locale bundle, or the
21
+ // bundle would shadow every later language switch.
29
22
  const dialog = createOgDialog({
30
- ...dialogOptions,
31
- locale: mergeLocale(origenUi.locale?.dialog, dialogOptions.locale),
23
+ ...origenUi.dialog,
32
24
  ...(locale ? { localeSource: computed(() => locale.value?.dialog) } : {}),
33
25
  } as Parameters<typeof createOgDialog>[0])
34
26
  const form = createOgForm({
35
- ...formOptions,
36
- locale: mergeLocale(origenUi.locale?.form, formOptions.locale),
27
+ ...origenUi.form,
37
28
  ...(locale ? { localeSource: computed(() => locale.value?.form) } : {}),
38
- permissions: formOptions.permissions ?? { has: permission.can },
39
- size: formOptions.size ?? origenUi.size,
29
+ permissions: origenUi.form.permissions ?? { has: permission.can },
30
+ size: origenUi.form.size ?? origenUi.size,
40
31
  } as Parameters<typeof createOgForm>[0])
41
32
  const table = createOgTable({
42
- ...tableOptions,
33
+ ...origenUi.table,
43
34
  config: {
44
- ...tableOptions.config,
45
- locale: mergeLocale(origenUi.locale?.table, tableOptions.config?.locale),
35
+ ...origenUi.table.config,
46
36
  permissions: {
47
37
  has: permission.can,
48
- ...tableOptions.config?.permissions,
38
+ ...origenUi.table.config?.permissions,
49
39
  },
50
40
  },
51
41
  ...(locale ? { localeSource: computed(() => locale.value?.table) } : {}),
52
42
  } as Parameters<typeof createOgTable>[0])
53
43
  const search = createOgSearch({
54
- ...searchOptions,
55
- config: {
56
- ...searchOptions.config,
57
- locale: mergeLocale(origenUi.locale.search, searchOptions.config?.locale),
58
- },
44
+ ...origenUi.search,
59
45
  ...(locale ? { localeSource: computed(() => locale.value?.search) } : {}),
60
- permissions: searchOptions.permissions ?? { has: permission.can },
61
- size: searchOptions.size ?? origenUi.size,
46
+ permissions: origenUi.search.permissions ?? { has: permission.can },
47
+ size: origenUi.search.size ?? origenUi.size,
62
48
  } as Parameters<typeof createOgSearch>[0])
63
49
  const tabs = createOgTabs({
64
- ...tabsOptions,
65
- locale: mergeLocale(origenUi.locale.tabs, tabsOptions.locale),
50
+ ...origenUi.tabs,
66
51
  ...(locale ? { localeSource: computed(() => locale.value?.tabs) } : {}),
67
52
  } as Parameters<typeof createOgTabs>[0])
68
53
 
@@ -0,0 +1,40 @@
1
+ // @vitest-environment jsdom
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
3
+
4
+ async function loadEmbeddedModule(): Promise<typeof import('./embedded')> {
5
+ vi.resetModules()
6
+ return await import('./embedded')
7
+ }
8
+
9
+ describe('embedded token bridge', () => {
10
+ beforeEach(() => {
11
+ vi.stubEnv('VITE_EMBEDDED', 'true')
12
+ ;(window as { __MICRO_APP_ENVIRONMENT__?: boolean }).__MICRO_APP_ENVIRONMENT__ = true
13
+ localStorage.clear()
14
+ })
15
+
16
+ afterEach(() => {
17
+ vi.unstubAllEnvs()
18
+ vi.resetModules()
19
+ localStorage.clear()
20
+ delete (window as { __MICRO_APP_ENVIRONMENT__?: boolean }).__MICRO_APP_ENVIRONMENT__
21
+ delete (window as { microApp?: unknown }).microApp
22
+ })
23
+
24
+ it('keeps host tokens in memory and exposes read-only storage', async () => {
25
+ const mod = await loadEmbeddedModule()
26
+ const storage = mod.embeddedTokenStorage
27
+ storage.setItem('token', 'attacker-token')
28
+ expect(storage.getItem('token')).toBeNull()
29
+ mod.startEmbeddedBridge()
30
+ expect(localStorage.length).toBe(0)
31
+ })
32
+
33
+ it('updates the in-memory token from host data without writing localStorage', async () => {
34
+ const mod = await loadEmbeddedModule()
35
+ ;(window as { microApp?: unknown }).microApp = { getData: () => ({ token: 'host-token' }) }
36
+ mod.startEmbeddedBridge()
37
+ expect(mod.embeddedTokenStorage.getItem('og-admin-access-token')).toBe('host-token')
38
+ expect(localStorage.length).toBe(0)
39
+ })
40
+ })
@@ -0,0 +1,135 @@
1
+ import type { BackendMenuNode } from './menuTypes'
2
+ // @vitest-environment jsdom
3
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
4
+
5
+ // embedded.ts 在模块加载时做嵌入探测(env 意图 + 运行时环境),
6
+ // 每个用例重置模块注册表并在 import 前布置好探测条件。
7
+ async function loadEmbeddedModule(): Promise<typeof import('./embedded')> {
8
+ vi.resetModules()
9
+ return await import('./embedded')
10
+ }
11
+
12
+ // fetchMenus 实际返回扁平列表(父子靠 parentPath 关联),夹具同构;
13
+ // order 升序排序:system(1) 应排在 dashboard(2) 之前
14
+ const menuNodes: BackendMenuNode[] = [
15
+ { code: 'dashboard', path: '/dashboard', title: '工作台', icon: 'Odometer', order: 2 },
16
+ { code: 'system', path: '/system', title: '系统管理', order: 1 },
17
+ { code: 'users', path: 'users', title: '用户管理', parentPath: '/system', order: 1 },
18
+ { code: 'audit', path: 'audit', title: '审计日志', parentPath: '/system', menu: false },
19
+ { code: 'profile', path: 'profile', title: '个人页' },
20
+ { code: 'secret', path: '/secret', title: '隐藏页', hidden: true },
21
+ ]
22
+
23
+ beforeEach(() => {
24
+ vi.stubEnv('VITE_EMBEDDED', 'true')
25
+ })
26
+
27
+ afterEach(() => {
28
+ vi.unstubAllEnvs()
29
+ vi.resetModules()
30
+ document.documentElement.classList.remove('dark')
31
+ delete (window as { __MICRO_APP_ENVIRONMENT__?: boolean }).__MICRO_APP_ENVIRONMENT__
32
+ delete (window as { __POWERED_BY_WUJIE__?: boolean }).__POWERED_BY_WUJIE__
33
+ delete (window as { microApp?: unknown }).microApp
34
+ delete (window as { $wujie?: unknown }).$wujie
35
+ })
36
+
37
+ describe('reportMenusToHost', () => {
38
+ it('运行时未探测到主壳环境时回退独立模式,上报 no-op', async () => {
39
+ const mod = await loadEmbeddedModule()
40
+ expect(mod.embeddedMode).toBe(false)
41
+ const dispatch = vi.fn()
42
+ ;(window as { microApp?: unknown }).microApp = { dispatch }
43
+ mod.reportMenusToHost(menuNodes)
44
+ expect(dispatch).not.toHaveBeenCalled()
45
+ })
46
+
47
+ it('micro-app 通道:过滤隐藏/非菜单节点,parentPath 链解析为绝对路由并重建两层', async () => {
48
+ ;(window as { __MICRO_APP_ENVIRONMENT__?: boolean }).__MICRO_APP_ENVIRONMENT__ = true
49
+ const mod = await loadEmbeddedModule()
50
+ expect(mod.embeddedMode).toBe(true)
51
+
52
+ const dispatch = vi.fn()
53
+ ;(window as { microApp?: unknown }).microApp = { dispatch }
54
+ mod.reportMenusToHost(menuNodes)
55
+
56
+ expect(dispatch).toHaveBeenCalledTimes(1)
57
+ expect(dispatch).toHaveBeenCalledWith({
58
+ event: 'sub-app-menu',
59
+ payload: {
60
+ menus: [
61
+ {
62
+ id: 'system',
63
+ title: '系统管理',
64
+ microRoute: '/system',
65
+ children: [{ id: 'users', title: '用户管理', microRoute: '/system/users' }],
66
+ },
67
+ { id: 'dashboard', title: '工作台', microRoute: '/dashboard', icon: 'Odometer' },
68
+ { id: 'profile', title: '个人页', microRoute: '/profile' },
69
+ ],
70
+ },
71
+ })
72
+ })
73
+
74
+ it('applyHostTheme:light/dark 切换 html.dark;非法值忽略', async () => {
75
+ ;(window as { __MICRO_APP_ENVIRONMENT__?: boolean }).__MICRO_APP_ENVIRONMENT__ = true
76
+ const mod = await loadEmbeddedModule()
77
+
78
+ mod.applyHostTheme({ theme: 'dark' })
79
+ expect(document.documentElement.classList.contains('dark')).toBe(true)
80
+ mod.applyHostTheme({ theme: 'light' })
81
+ expect(document.documentElement.classList.contains('dark')).toBe(false)
82
+ mod.applyHostTheme({ theme: 'blue' })
83
+ mod.applyHostTheme({})
84
+ expect(document.documentElement.classList.contains('dark')).toBe(false)
85
+ })
86
+
87
+ it('reportMenusToHost:父节点相对 path 也能解析绝对子路由并挂载子项', async () => {
88
+ ;(window as { __MICRO_APP_ENVIRONMENT__?: boolean }).__MICRO_APP_ENVIRONMENT__ = true
89
+ const dispatch = vi.fn()
90
+ ;(window as { microApp?: unknown }).microApp = { dispatch }
91
+ const mod = await loadEmbeddedModule()
92
+
93
+ mod.reportMenusToHost([
94
+ { code: 'system', path: 'system', title: '系统管理' },
95
+ { code: 'users', path: 'users', title: '用户管理', parentPath: '/system' },
96
+ ])
97
+
98
+ expect(dispatch).toHaveBeenCalledWith({
99
+ event: 'sub-app-menu',
100
+ payload: {
101
+ menus: [
102
+ {
103
+ id: 'system',
104
+ title: '系统管理',
105
+ microRoute: '/system',
106
+ children: [{ id: 'users', title: '用户管理', microRoute: '/system/users' }],
107
+ },
108
+ ],
109
+ },
110
+ })
111
+ })
112
+
113
+ it('wujie 通道:$emit 消息为 { event, payload } 包裹,与主壳 onBusEvent 解析同构', async () => {
114
+ ;(window as { __POWERED_BY_WUJIE__?: boolean }).__POWERED_BY_WUJIE__ = true
115
+ const mod = await loadEmbeddedModule()
116
+ expect(mod.embeddedMode).toBe(true)
117
+
118
+ const $emit = vi.fn()
119
+ ;(window as { $wujie?: unknown }).$wujie = { bus: { $emit, $on: vi.fn(), $off: vi.fn() } }
120
+
121
+ mod.reportMenusToHost([{ code: 'home', path: 'home', title: '首页' }])
122
+ expect($emit).toHaveBeenCalledWith('sub-app-menu', {
123
+ event: 'sub-app-menu',
124
+ payload: { menus: [{ id: 'home', title: '首页', microRoute: '/home' }] },
125
+ })
126
+
127
+ // 401 通知同走统一出口
128
+ ;($emit as ReturnType<typeof vi.fn>).mockClear()
129
+ mod.notifyHostUnauthorized()
130
+ expect($emit).toHaveBeenCalledWith('sub-app-error', {
131
+ event: 'sub-app-error',
132
+ payload: { code: 'unauthorized' },
133
+ })
134
+ })
135
+ })
@@ -0,0 +1,255 @@
1
+ import type { BackendMenuNode } from './menuTypes'
2
+
3
+ // 微前端嵌入模式(architecture.md M4 §5):
4
+ // VITE_EMBEDDED=true 表达嵌入意图;运行时必须探测到主壳注入的环境,
5
+ // 否则回退独立模式并告警——防止误配置导致应用在无主壳时丢失自身外壳。
6
+ // 双框架桥:wujie(props 一次性 + bus 事件)与 micro-app(data 通道)。
7
+
8
+ const wantsEmbedded = import.meta.env.VITE_EMBEDDED === 'true'
9
+
10
+ /** Embedded token storage is intentionally volatile and read-only to consumers. */
11
+ let embeddedAccessToken: string | null = null
12
+ export const embeddedTokenStorage = {
13
+ getItem: (_key: string): string | null => embeddedAccessToken,
14
+ setItem: (_key: string, _value: string): void => undefined,
15
+ removeItem: (_key: string): void => {
16
+ embeddedAccessToken = null
17
+ },
18
+ }
19
+
20
+ export type HostFramework = 'wujie' | 'micro-app'
21
+
22
+ interface WujieChildApi {
23
+ props?: Record<string, unknown>
24
+ bus?: {
25
+ $emit: (event: string, ...args: unknown[]) => void
26
+ $on: (event: string, callback: (...args: unknown[]) => void) => void
27
+ $off: (event: string, callback: (...args: unknown[]) => void) => void
28
+ }
29
+ }
30
+
31
+ interface MicroAppChildApi {
32
+ getData?: () => Record<string, unknown>
33
+ addDataListener?: (
34
+ callback: (data: Record<string, unknown>) => void,
35
+ autoTrigger?: boolean,
36
+ ) => void
37
+ dispatch?: (data: Record<string, unknown>) => void
38
+ }
39
+
40
+ declare global {
41
+ interface Window {
42
+ __POWERED_BY_WUJIE__?: boolean
43
+ __MICRO_APP_ENVIRONMENT__?: boolean
44
+ __MICRO_APP_NAME__?: string
45
+ $wujie?: WujieChildApi
46
+ microApp?: MicroAppChildApi
47
+ }
48
+ }
49
+
50
+ function detectHostFramework(): HostFramework | null {
51
+ if (typeof window === 'undefined') return null
52
+ if (window.__POWERED_BY_WUJIE__) return 'wujie'
53
+ if (window.__MICRO_APP_ENVIRONMENT__ === true || window.__MICRO_APP_NAME__ !== undefined) {
54
+ return 'micro-app'
55
+ }
56
+ return null
57
+ }
58
+
59
+ const detected = detectHostFramework()
60
+ export const hostFramework: HostFramework | null = wantsEmbedded ? detected : null
61
+ export const embeddedMode = hostFramework !== null
62
+
63
+ if (wantsEmbedded && detected === null) {
64
+ console.warn('[admin] VITE_EMBEDDED=true 但未检测到主壳注入环境,已回退独立模式')
65
+ }
66
+
67
+ function wujieProps(): Record<string, unknown> {
68
+ return window.$wujie?.props ?? {}
69
+ }
70
+
71
+ function microAppData(): Record<string, unknown> {
72
+ return window.microApp?.getData?.() ?? {}
73
+ }
74
+
75
+ /** 主壳注入数据快照(wujie 走 props,micro-app 走 data 缓存) */
76
+ export function readHostInjection(): Record<string, unknown> {
77
+ if (!embeddedMode) return {}
78
+ return hostFramework === 'wujie' ? wujieProps() : microAppData()
79
+ }
80
+
81
+ function applyToken(data: Record<string, unknown> | undefined): void {
82
+ const token = data?.token
83
+ if (typeof token === 'string' && token !== '') embeddedAccessToken = token
84
+ }
85
+
86
+ /**
87
+ * 主壳明暗主题跟随(architecture.md §4.1):与 admin 暗色 token 的
88
+ * :root.dark 约定一致;非法值忽略。嵌入模式下本桥持有 dark class
89
+ * 的所有权(独立模式仍由 admin 自身主题 store 负责,见 App.vue)。
90
+ */
91
+ export function applyHostTheme(data: Record<string, unknown> | undefined): void {
92
+ const theme = data?.theme
93
+ if (theme !== 'light' && theme !== 'dark') return
94
+ if (typeof document === 'undefined') return
95
+ document.documentElement.classList.toggle('dark', theme === 'dark')
96
+ }
97
+
98
+ /**
99
+ * 嵌入模式桥接:token 由主壳唯一持有并推送,本应用只写存储
100
+ * (TokenManager 每次请求先读存储);刷新被冻结,401 时通知主壳。
101
+ * 主题由主壳下发:注入时应用一次,micro-app 通道持续监听变更
102
+ * (wujie 的 props 一次性注入,仅支持挂载时初始主题)。
103
+ */
104
+ export function startEmbeddedBridge(): void {
105
+ if (!embeddedMode) return
106
+ applyToken(readHostInjection())
107
+ applyHostTheme(readHostInjection())
108
+ if (hostFramework === 'micro-app') {
109
+ window.microApp?.addDataListener?.(applyToken, false)
110
+ window.microApp?.addDataListener?.(applyHostTheme, false)
111
+ }
112
+ // wujie 的 props 在 mount 时注入;admin 为单实例嵌入,无会话中途轮换需求
113
+ }
114
+
115
+ /** 嵌入模式通知主壳:认证失效(主壳决定重新登录/刷新) */
116
+ export function notifyHostUnauthorized(): void {
117
+ if (!embeddedMode) return
118
+ dispatchToHost('sub-app-error', { code: 'unauthorized' })
119
+ }
120
+
121
+ /** 子应用→主壳菜单上报单项(主壳契约 SubAppMenuItem 的同构最小集) */
122
+ interface HostMenuItemReport {
123
+ id: string
124
+ title: string
125
+ microRoute: string
126
+ icon?: string
127
+ children?: HostMenuItemReport[]
128
+ }
129
+
130
+ /** 子应用→主壳上报事件(与主壳 SubToHostMessage 白名单同构) */
131
+ type HostBridgeEvent = 'sub-app-error' | 'sub-app-menu'
132
+
133
+ /** 事件统一出口:wujie 走 bus $emit,micro-app 走 dispatch(契约消息结构一致) */
134
+ function dispatchToHost(event: HostBridgeEvent, payload: unknown): void {
135
+ const appId = readHostInjection().appId
136
+ const message = { event, ...(typeof appId === 'string' ? { appId } : {}), payload }
137
+ if (hostFramework === 'wujie') {
138
+ window.$wujie?.bus?.$emit(event, message)
139
+ return
140
+ }
141
+ window.microApp?.dispatch?.(message)
142
+ }
143
+
144
+ // 与 router/dynamicRoutes.ts 的 fullPath 同语义:绝对 path 直用;相对 path
145
+ // 拼接父链前缀,无父链时补 "/" 根前缀。主壳契约要求 microRoute 以 / 开头。
146
+ function resolveMicroRoute(prefix: string, path: string): string {
147
+ const trimmed = path.trim()
148
+ if (trimmed.startsWith('/')) return trimmed
149
+ if (prefix === '') return `/${trimmed}`
150
+ return `${prefix.replace(/\/$/, '')}/${trimmed}`
151
+ }
152
+
153
+ // BackendMenuNode → 上报契约。fetchMenus 返回扁平列表(父子靠 parentPath
154
+ // 关联,树由路由适配层构建),这里重建两层结构(契约上限):
155
+ // 1. 按 parentPath 链解析每个节点的绝对 microRoute(dynamicRoutes.fullPath 同语义);
156
+ // 2. 父节点本身是顶层(目录)时子项挂为其 children,更深的层级拍平到顶层。
157
+ // 隐藏/非菜单节点过滤;保持后端给定顺序,权限过滤已由菜单装载链完成。
158
+ function toMenuReport(nodes: readonly BackendMenuNode[]): HostMenuItemReport[] {
159
+ // order 升序(缺省排后,稳定排序保持原有相对顺序),与 admin 自身菜单一致
160
+ const usable = nodes
161
+ .filter((node) => node.menu !== false && node.hidden !== true)
162
+ .sort((a, b) => (a.order ?? Number.POSITIVE_INFINITY) - (b.order ?? Number.POSITIVE_INFINITY))
163
+
164
+ const byPath = new Map<string, BackendMenuNode[]>()
165
+ for (const node of usable) {
166
+ const path = node.path.trim()
167
+ byPath.set(path, [...(byPath.get(path) ?? []), node])
168
+ }
169
+
170
+ const fullPathMemo = new Map<BackendMenuNode, string>()
171
+ function fullPathOf(node: BackendMenuNode, seen: Set<string>): string | undefined {
172
+ const cached = fullPathMemo.get(node)
173
+ if (cached !== undefined) return cached
174
+ if (seen.has(node.code)) return undefined
175
+ seen.add(node.code)
176
+ const path = node.path.trim()
177
+ if (path === '') return undefined
178
+ let resolved: string
179
+ if (path.startsWith('/')) {
180
+ resolved = path
181
+ } else {
182
+ const parentPath = node.parentPath?.trim()
183
+ const rawCandidates = parentPath ? (byPath.get(parentPath) ?? []) : []
184
+ const canonicalCandidates = parentPath
185
+ ? usable.filter((candidate) => fullPathOf(candidate, new Set(seen)) === parentPath)
186
+ : []
187
+ const candidates = [...new Set([...rawCandidates, ...canonicalCandidates])].filter(
188
+ (candidate) => candidate !== node,
189
+ )
190
+ const parent = candidates.length === 1 ? candidates[0] : undefined
191
+ const parentFullPath = parent ? fullPathOf(parent, seen) : undefined
192
+ resolved = parentFullPath === undefined ? `/${path}` : resolveMicroRoute(parentFullPath, path)
193
+ }
194
+ fullPathMemo.set(node, resolved)
195
+ return resolved
196
+ }
197
+
198
+ const itemsByNode = new Map<BackendMenuNode, HostMenuItemReport>()
199
+ for (const node of usable) {
200
+ const microRoute = fullPathOf(node, new Set())
201
+ if (microRoute === undefined) continue
202
+ itemsByNode.set(node, {
203
+ id: node.code,
204
+ title: node.title,
205
+ microRoute,
206
+ ...(node.icon !== undefined ? { icon: node.icon } : {}),
207
+ })
208
+ }
209
+
210
+ function parentOf(node: BackendMenuNode): BackendMenuNode | undefined {
211
+ const parentPath = node.parentPath?.trim()
212
+ if (!parentPath) return undefined
213
+ const rawCandidates = byPath.get(parentPath) ?? []
214
+ const canonicalCandidates = usable.filter(
215
+ (candidate) => fullPathMemo.get(candidate) === parentPath,
216
+ )
217
+ const candidates = [...new Set([...rawCandidates, ...canonicalCandidates])].filter(
218
+ (candidate) => candidate !== node,
219
+ )
220
+ return candidates.length === 1 ? candidates[0] : undefined
221
+ }
222
+
223
+ // 父节点自身无可用父级(即目录层)时,子项挂为其 children;
224
+ // 更深的层级拍平到顶层,满足契约两层上限。
225
+ const tops: HostMenuItemReport[] = []
226
+ for (const node of usable) {
227
+ const item = itemsByNode.get(node)
228
+ if (!item) continue
229
+ const parent = parentOf(node)
230
+ const parentItem = parent !== undefined ? itemsByNode.get(parent) : undefined
231
+ const parentIsTopLevel =
232
+ parentItem !== undefined && (parent === undefined || parentOf(parent) === undefined)
233
+ if (parentItem !== undefined && parentIsTopLevel) {
234
+ if (parentItem.children === undefined) parentItem.children = []
235
+ parentItem.children.push(item)
236
+ } else {
237
+ tops.push(item)
238
+ }
239
+ }
240
+ return tops
241
+ }
242
+
243
+ /**
244
+ * 嵌入模式向主壳上报权限过滤后的菜单树(sub-app-menu 事件,
245
+ * architecture.md §3 过渡聚合源):主壳据此在侧栏渲染应用分组导航。
246
+ * 上报失败只告警,不影响本应用启动与运行;独立模式 no-op。
247
+ */
248
+ export function reportMenusToHost(nodes: readonly BackendMenuNode[]): void {
249
+ if (!embeddedMode) return
250
+ try {
251
+ dispatchToHost('sub-app-menu', { menus: toMenuReport(nodes) })
252
+ } catch (cause) {
253
+ console.warn('[admin] menu report to host failed (non-blocking)', cause)
254
+ }
255
+ }
@@ -0,0 +1,52 @@
1
+ import { currentAdminLocale } from './adminLocale'
2
+
3
+ export { currentAdminLocale }
4
+
5
+ type DateTimeFormatOptions = Intl.DateTimeFormatOptions
6
+
7
+ const formatterCache = new Map<string, Intl.DateTimeFormat>()
8
+
9
+ function formatter(options: DateTimeFormatOptions, key: string): Intl.DateTimeFormat {
10
+ const cacheKey = `${currentAdminLocale()}|${key}`
11
+ const cached = formatterCache.get(cacheKey)
12
+ if (cached) return cached
13
+ const created = new Intl.DateTimeFormat(currentAdminLocale(), options)
14
+ formatterCache.set(cacheKey, created)
15
+ return created
16
+ }
17
+
18
+ function format(value: unknown, options: DateTimeFormatOptions, key: string): string {
19
+ const date = new Date(String(value))
20
+ return Number.isNaN(date.valueOf()) ? '-' : formatter(options, key).format(date)
21
+ }
22
+
23
+ /** Formats a calendar date (year-month-day) in the active locale. */
24
+ export function formatAdminDate(value: unknown): string {
25
+ return format(value, { year: 'numeric', month: '2-digit', day: '2-digit' }, 'date')
26
+ }
27
+
28
+ /** Formats a full timestamp (date plus hours-minutes-seconds) in the active locale. */
29
+ export function formatAdminDateTime(value: unknown): string {
30
+ return format(
31
+ value,
32
+ {
33
+ year: 'numeric',
34
+ month: '2-digit',
35
+ day: '2-digit',
36
+ hour: '2-digit',
37
+ minute: '2-digit',
38
+ second: '2-digit',
39
+ hour12: false,
40
+ },
41
+ 'dateTime',
42
+ )
43
+ }
44
+
45
+ /** Formats a compact timestamp (month-day hours-minutes) in the active locale. */
46
+ export function formatAdminShortDateTime(value: unknown): string {
47
+ return format(
48
+ value,
49
+ { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false },
50
+ 'shortDateTime',
51
+ )
52
+ }