@crombolo/backoffice-host 0.60.0 → 0.61.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.
@@ -2,7 +2,7 @@
2
2
  "$schema": "../../backoffice-dist/dist/umbraco-package-schema.json",
3
3
  "name": "Crombolo",
4
4
  "id": "Crombolo.Core",
5
- "version": "0.60.0",
5
+ "version": "0.61.0",
6
6
  "allowPublicAccess": false,
7
7
  "extensions": [
8
8
  {
@@ -531,7 +531,7 @@
531
531
  "conditions": [
532
532
  {
533
533
  "alias": "Umb.Condition.SectionUserPermission",
534
- "match": "Crombolo.Section.AllSettings"
534
+ "match": "Umb.Section.Settings"
535
535
  }
536
536
  ]
537
537
  },
@@ -663,7 +663,7 @@
663
663
  "conditions": [
664
664
  {
665
665
  "alias": "Umb.Condition.SectionUserPermission",
666
- "match": "Crombolo.Section.WorkflowSetup"
666
+ "match": "Umb.Section.Settings"
667
667
  }
668
668
  ]
669
669
  },
@@ -787,36 +787,6 @@
787
787
  "name": "Crombolo Approvals Active Condition",
788
788
  "api": "/crombolo-plugin/approvals-active.js"
789
789
  },
790
- {
791
- "type": "section",
792
- "alias": "Crombolo.Section.Structure",
793
- "name": "Crombolo Structure Section",
794
- "weight": 30,
795
- "meta": {
796
- "label": "Structure",
797
- "pathname": "structure"
798
- }
799
- },
800
- {
801
- "type": "section",
802
- "alias": "Crombolo.Section.Components",
803
- "name": "Crombolo Code Section",
804
- "weight": 29,
805
- "meta": {
806
- "label": "Code",
807
- "pathname": "components"
808
- }
809
- },
810
- {
811
- "type": "section",
812
- "alias": "Crombolo.Section.WorkflowSetup",
813
- "name": "Crombolo Workflow setup Section",
814
- "weight": 28,
815
- "meta": {
816
- "label": "Workflow setup",
817
- "pathname": "workflow-setup"
818
- }
819
- },
820
790
  {
821
791
  "type": "section",
822
792
  "alias": "Crombolo.Section.Workflow",
@@ -879,7 +849,7 @@
879
849
  },
880
850
  {
881
851
  "alias": "Umb.Condition.SectionUserPermission",
882
- "match": "Crombolo.Section.WorkflowSetup"
852
+ "match": "Umb.Section.Settings"
883
853
  }
884
854
  ]
885
855
  },
@@ -6,9 +6,10 @@
6
6
  * marketplace, the server half and the installer cannot disagree about what a
7
7
  * bundle is.
8
8
  */
9
- import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
9
+ import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs'
10
10
  import { dirname, join, normalize } from 'node:path'
11
11
  import { BACKOFFICE_CODE, permissionsProblem, readSettings } from './bundle-permissions.ts'
12
+ import { packageInRoot, readRecord, rootOf } from './extension-roots.ts'
12
13
  import type { PackageManifestImportmap } from './manifests.ts'
13
14
 
14
15
  /** The package a bundle declares its peer range on. */
@@ -83,15 +84,54 @@ export interface CromboloField {
83
84
  }
84
85
 
85
86
  /**
86
- * The bundle schema an extension with code must be written for: 5 put its server
87
- * half in `src/server/` and its back-office code in `src/backoffice/` (story 320);
88
- * 4 gave each permission a reason (308); 3 declared them (222); 2 made its routes
89
- * route handlers (211).
87
+ * The bundle schema this release writes: 6 lets a manifest entry name a screen
88
+ * its server half describes (story 323); 5 put its server half in `src/server/`
89
+ * and its back-office code in `src/backoffice/` (story 320); 4 gave each
90
+ * permission a reason (308); 3 declared them (222); 2 made its routes route
91
+ * handlers (211).
90
92
  */
91
- export const BUNDLE_SCHEMA_VERSION = 5
93
+ export const BUNDLE_SCHEMA_VERSION = 6
92
94
 
93
- /** The oldest schema read: an extension at 4 or before is refused until it is migrated (story 320). */
94
- export const OLDEST_BUNDLE_SCHEMA_VERSION = 5
95
+ /** The schema whose manifest entries may name a described screen (story 323). */
96
+ export const SCREEN_SCHEMA_VERSION = 6
97
+
98
+ const SCREEN_ID = /^[a-z][a-z0-9-]{0,39}$/
99
+
100
+ /**
101
+ * Why its manifest's entries cannot name the screens they do (story 323): a
102
+ * screen needs schema 6 and a server half to describe it, and an entry names a
103
+ * screen or a module, never both. Pure.
104
+ */
105
+ export function screenEntryProblems(f: Record<string, unknown>, schema: number): string[] {
106
+ if (!Array.isArray(f.extensions)) return []
107
+ const problems: string[] = []
108
+ for (const entry of f.extensions) {
109
+ if (!isPlainObject(entry) || entry.screen === undefined) continue
110
+ const alias = typeof entry.alias === 'string' ? entry.alias : 'an entry'
111
+ if (typeof entry.screen !== 'string' || !SCREEN_ID.test(entry.screen))
112
+ problems.push(
113
+ `${alias} names the screen ${JSON.stringify(entry.screen)}, which is not a screen id`,
114
+ )
115
+ else if (schema < SCREEN_SCHEMA_VERSION)
116
+ problems.push(
117
+ `${alias} names a screen, which needs "crombolo.schemaVersion": ${SCREEN_SCHEMA_VERSION}`,
118
+ )
119
+ if (entry.element !== undefined || entry.js !== undefined)
120
+ problems.push(`${alias} names a screen and a module: it is drawn from one or the other`)
121
+ if (f.server === undefined)
122
+ problems.push(`${alias} names a screen, and the package has no server half to describe it`)
123
+ }
124
+ return problems
125
+ }
126
+
127
+ /**
128
+ * The oldest schema read: an extension at 5 or before is refused until it is
129
+ * migrated (stories 320, 329).
130
+ */
131
+ export const OLDEST_BUNDLE_SCHEMA_VERSION = 6
132
+
133
+ /** The schema that put an extension's code in `src/server/` and `src/backoffice/` (story 320). */
134
+ export const LAYOUT_SCHEMA_VERSION = 5
95
135
 
96
136
  /**
97
137
  * The oldest server half the site's config may still wire in itself: its own
@@ -175,6 +215,18 @@ export interface BundlePackage {
175
215
  /** The package's directory, when it carries content: the payload is the package. */
176
216
  contentDir: string | undefined
177
217
  carries: { extensions: boolean; content: boolean; server: boolean }
218
+ /** Its root, `extensions/<id>/`, when it was installed into one (story 326). */
219
+ root?: string
220
+ /**
221
+ * An extension the site lists as a dependency, the way before story 326: run
222
+ * only when the site's config wires it, as the site's own code.
223
+ */
224
+ dependency?: true
225
+ /**
226
+ * A dependency that is a link to a package on this machine, a workspace's or
227
+ * one `bun link` made: a developer's, allowed outside production (story 326).
228
+ */
229
+ linked?: true
178
230
  }
179
231
 
180
232
  export interface PackageJson {
@@ -217,12 +269,14 @@ export function schemaProblem(schema: number, options: { wired?: boolean } = {})
217
269
  ? 'it declares the permissions it needs in "crombolo.permissions" (docs/bundles.md, "Permissions")'
218
270
  : '',
219
271
  schema < 4 && !options.wired ? 'each permission gives its reason' : '',
220
- options.wired
272
+ options.wired || schema >= LAYOUT_SCHEMA_VERSION
221
273
  ? ''
222
- : `its server code moves to ${SERVER_DIR}/ and its back-office code to ${BACKOFFICE_DIR}/, which \`crombolo extension migrate <dir>\` does`,
274
+ : `its server code moves to ${SERVER_DIR}/ and its back-office code to ${BACKOFFICE_DIR}/`,
275
+ options.wired ? '' : '"actAs" becomes "user.delegate" (story 325)',
223
276
  ].filter(Boolean)
277
+ const migrate = options.wired ? '' : ', which `crombolo extension migrate <dir>` does'
224
278
  const reads = options.wired ? OLDEST_WIRED_SCHEMA_VERSION : BUNDLE_SCHEMA_VERSION
225
- return `it is written for bundle schema ${schema}, and this release reads ${reads}${options.wired ? ` to ${BUNDLE_SCHEMA_VERSION}` : ''}: ${changes.join(', and ')}, with "crombolo.schemaVersion": ${BUNDLE_SCHEMA_VERSION}${options.wired ? '' : '; then publish it again'}`
279
+ return `it is written for bundle schema ${schema}, and this release reads ${reads}${options.wired ? ` to ${BUNDLE_SCHEMA_VERSION}` : ''}: ${changes.join(', and ')}, with "crombolo.schemaVersion": ${BUNDLE_SCHEMA_VERSION}${migrate}${options.wired ? '' : '; then publish it again'}`
226
280
  }
227
281
 
228
282
  /**
@@ -351,7 +405,7 @@ export function validateBundlePackage(json: PackageJson, directory?: string): st
351
405
  else if (f.permissions !== undefined) {
352
406
  const problem = permissionsProblem(f.permissions, schema)
353
407
  if (problem) problems.push(problem)
354
- else if (schema >= BUNDLE_SCHEMA_VERSION) {
408
+ else if (schema >= OLDEST_BUNDLE_SCHEMA_VERSION) {
355
409
  const asksForCode = Object.hasOwn(f.permissions as object, BACKOFFICE_CODE)
356
410
  if (modules.length > 0 && !asksForCode)
357
411
  problems.push(
@@ -384,6 +438,8 @@ export function validateBundlePackage(json: PackageJson, directory?: string): st
384
438
  )
385
439
  }
386
440
 
441
+ problems.push(...screenEntryProblems(f, schema))
442
+
387
443
  const hasExtensions = Array.isArray(f.extensions) && f.extensions.length > 0
388
444
  if (!hasExtensions && f.content === undefined && f.server === undefined)
389
445
  problems.push(
@@ -507,6 +563,25 @@ export interface DiscoveredBundles {
507
563
  export function discoverBundles(siteDir: string): DiscoveredBundles {
508
564
  const json = readPackageJson(join(siteDir, 'package.json'))
509
565
  const found: DiscoveredBundles = { bundles: [], problems: [] }
566
+ // Story 326: what the record names, each from its own root.
567
+ const seen = new Set<string>()
568
+ for (const [id, line] of Object.entries(readRecord(siteDir)).sort(([a], [b]) =>
569
+ a.localeCompare(b),
570
+ )) {
571
+ const directory = packageInRoot(siteDir, id, line.name)
572
+ if (!existsSync(join(directory, 'package.json'))) continue
573
+ const read = readBundlePackage(directory)
574
+ seen.add(line.name)
575
+ if (read.bundle?.bundleType === 'site')
576
+ found.problems.push({ packageName: line.name, problems: [SITE_PACKAGE_NOT_INSTALLED] })
577
+ else if (read.bundle) found.bundles.push({ ...read.bundle, root: rootOf(siteDir, id) })
578
+ else if (read.problems.length > 0)
579
+ found.problems.push({
580
+ packageName: line.name,
581
+ problems: read.problems,
582
+ ...(read.untyped ? { untyped: read.untyped } : {}),
583
+ })
584
+ }
510
585
  // A peer is declared too: a site whose host provides `@crombolo/*` lists
511
586
  // them there (story 192).
512
587
  const names = new Set([
@@ -514,12 +589,20 @@ export function discoverBundles(siteDir: string): DiscoveredBundles {
514
589
  ...Object.keys(json?.peerDependencies ?? {}),
515
590
  ])
516
591
  for (const name of [...names].sort()) {
592
+ if (seen.has(name)) continue
517
593
  const directory = resolvePackageDir(siteDir, name)
518
594
  if (!directory) continue
519
595
  const read = readBundlePackage(directory)
520
596
  if (read.bundle?.bundleType === 'site')
521
597
  found.problems.push({ packageName: name, problems: [SITE_PACKAGE_NOT_INSTALLED] })
522
- else if (read.bundle) found.bundles.push(read.bundle)
598
+ else if (read.bundle)
599
+ found.bundles.push(
600
+ read.bundle.bundleType !== 'extension'
601
+ ? read.bundle
602
+ : isLinked(directory)
603
+ ? { ...read.bundle, linked: true }
604
+ : { ...read.bundle, dependency: true },
605
+ )
523
606
  else if (read.problems.length > 0)
524
607
  found.problems.push({
525
608
  packageName: name,
@@ -530,6 +613,15 @@ export function discoverBundles(siteDir: string): DiscoveredBundles {
530
613
  return found
531
614
  }
532
615
 
616
+ /** Whether a package directory is a link to one elsewhere on this machine, as a workspace's is. */
617
+ function isLinked(directory: string): boolean {
618
+ try {
619
+ return lstatSync(directory).isSymbolicLink() || realpathSync(directory) !== directory
620
+ } catch {
621
+ return false
622
+ }
623
+ }
624
+
533
625
  /** Whether a path is a directory, for telling a package path from a package name. */
534
626
  export function isDirectory(path: string): boolean {
535
627
  try {
@@ -38,7 +38,9 @@ export const BUNDLE_PERMISSIONS = {
38
38
  'identityProviders.write': "Change administrators' settings for those sign-in providers",
39
39
  'member.delegate':
40
40
  'Act for a signed-in member who uses it: what it adds is theirs, and it sees only what they may see',
41
- actAs: 'Act for a back-office user, as chosen when it is granted, within what that user may do',
41
+ // Story 325: as wide as the person using it, and recorded against them.
42
+ 'user.delegate':
43
+ 'Act for the person using it in the back office: it can do anything they can do here, and everything it does is recorded against them',
42
44
  'events.content': 'Be told when pages are saved, published, moved or deleted',
43
45
  'http.outbound':
44
46
  'Send requests from the server, and from its screens in your browser, to the addresses it names',
@@ -72,10 +74,139 @@ export const BACKOFFICE_CODE = 'backoffice.code'
72
74
  * what its signature shows.
73
75
  */
74
76
  export const BACKOFFICE_CODE_WARNING =
75
- "Its screens act as whoever is signed in, with everything that person can do on this site. Unlike the rest of an extension, this part can't be kept apart from the site. Don't install this from a publisher you don't trust."
77
+ "Runs its own code inside your back office, with the same access as the site's own code. Nothing it does there can be watched or limited. Only install this from a publisher you trust as you trust your own developers."
76
78
 
77
- /** Never offered, whatever an extension asks: writing users could make anyone an administrator. */
78
- export const NEVER_OFFERED: ReadonlySet<string> = new Set(['users.write'])
79
+ /** The permission to act for the person using it (story 325). */
80
+ export const USER_DELEGATE = 'user.delegate'
81
+
82
+ /** What the install says beside `user.delegate`. */
83
+ export const USER_DELEGATE_DETAIL =
84
+ 'When nobody is using it, for a scheduled job or an event, it acts for whoever granted it instead. It may never install or grant extensions, or change users and groups, for anyone.'
85
+
86
+ /** Each area's read and write, which `user.delegate` already covers. */
87
+ export const AREA_PERMISSIONS: readonly string[] = Object.keys(BUNDLE_PERMISSIONS).filter(
88
+ (permission) => /^[a-zA-Z]+\.(read|write)$/.test(permission),
89
+ )
90
+
91
+ /**
92
+ * Never offered, whatever an extension asks: writing users could make anyone an
93
+ * administrator, and no extension brings in another or widens a grant (story 324).
94
+ */
95
+ export const NEVER_OFFERED: ReadonlySet<string> = new Set([
96
+ 'users.write',
97
+ 'extensions.install',
98
+ 'extensions.grant',
99
+ ])
100
+
101
+ /** Why each never-offered permission is refused, said where it is asked for. */
102
+ const NEVER_OFFERED_WHY: Readonly<Record<string, string>> = {
103
+ 'users.write': 'only an administrator changes users',
104
+ 'extensions.install': 'no extension brings in another',
105
+ 'extensions.grant': 'no extension widens what it, or another, was granted',
106
+ }
107
+
108
+ /**
109
+ * How far an extension reaches, computed from what it asks for and never
110
+ * declared (story 324): `backoffice.code` runs unconfined in the back office,
111
+ * `user.delegate` acts as the person using it, and anything else is limited.
112
+ */
113
+ export type AccessLevel = 'limited' | 'acts-as-you' | 'unrestricted'
114
+
115
+ /** The level a list of permissions adds up to: the highest thing in it. Pure. */
116
+ export function levelOf(permissions: readonly string[]): AccessLevel {
117
+ if (permissions.includes(BACKOFFICE_CODE)) return 'unrestricted'
118
+ if (permissions.includes(USER_DELEGATE)) return 'acts-as-you'
119
+ return 'limited'
120
+ }
121
+
122
+ /** Whether a level is one of the two only an administrator grants. */
123
+ export const isUpperLevel = (level: AccessLevel) => level !== 'limited'
124
+
125
+ /** The badge and the sentence under it, per level (the maintainer's words). */
126
+ export const LEVEL_WORDS: Readonly<Record<AccessLevel, { label: string; sentence: string }>> = {
127
+ limited: {
128
+ label: 'Limited',
129
+ sentence:
130
+ 'Works through the site with only the access below. You can see everything it does and undo it.',
131
+ },
132
+ 'acts-as-you': {
133
+ label: 'Acts as you',
134
+ sentence:
135
+ 'Can do anything on this site that the person using it can do. Everything it does is recorded against them.',
136
+ },
137
+ unrestricted: {
138
+ label: 'Unrestricted',
139
+ sentence:
140
+ "Runs its own code inside your back office, with the same access as the site's own code. Nothing it does there can be watched or limited. Only install this from a publisher you trust as you trust your own developers.",
141
+ },
142
+ }
143
+
144
+ /** What each area is called in the four groups. */
145
+ const AREA_WORDS: Readonly<Record<string, string>> = {
146
+ content: 'pages',
147
+ media: 'media',
148
+ members: 'members',
149
+ users: 'back-office users',
150
+ forms: 'forms',
151
+ formEntries: 'form entries',
152
+ dictionary: 'dictionary words',
153
+ contentTypes: 'content types',
154
+ webhooks: 'webhooks',
155
+ workflows: 'approval workflows',
156
+ redirects: 'redirects',
157
+ identityProviders: 'sign-in providers',
158
+ }
159
+
160
+ /** What an extension adds, by the permission that says so. */
161
+ const ADDS_WORDS: Readonly<Record<string, string>> = {
162
+ 'routes.public': 'addresses on the site anyone may visit',
163
+ 'events.content': 'something that runs when pages change',
164
+ 'data.tables': 'its own data',
165
+ templates: 'page templates',
166
+ [BACKOFFICE_CODE]: 'its own code in your back office',
167
+ }
168
+
169
+ /** The four groups the install panel shows, and who it acts as when it asks to. */
170
+ export interface PermissionGroups {
171
+ sees: string[]
172
+ changes: string[]
173
+ sendsTo: string[]
174
+ adds: string[]
175
+ actsAs: string[]
176
+ }
177
+
178
+ /**
179
+ * The catalogue folded into what an administrator reads at a glance (story
180
+ * 324): Sees, Changes, Sends to and Adds, with Acts as when it asks to. Each
181
+ * permission lands in exactly one place. Pure.
182
+ */
183
+ export function groupsOf(
184
+ declared: readonly (string | DeclaredPermission)[],
185
+ options: { screens?: number } = {},
186
+ ): PermissionGroups {
187
+ const groups: PermissionGroups = { sees: [], changes: [], sendsTo: [], adds: [], actsAs: [] }
188
+ const entries = declared.map((entry) =>
189
+ typeof entry === 'string' ? { permission: entry, reason: null } : entry,
190
+ )
191
+ for (const { permission, origins } of entries) {
192
+ const [area, verb] = permission.split('.')
193
+ if (permission === USER_DELEGATE) {
194
+ groups.sees.push('everything you can see')
195
+ groups.changes.push('everything you can change')
196
+ groups.actsAs.push('you, or whoever uses it')
197
+ } else if (permission === 'member.delegate') groups.actsAs.push('members who use it')
198
+ else if (permission === 'http.outbound')
199
+ groups.sendsTo.push(...(origins ?? []).map((origin) => origin.replace(/^https?:\/\//, '')))
200
+ else if (ADDS_WORDS[permission]) groups.adds.push(ADDS_WORDS[permission] as string)
201
+ else if (area && AREA_WORDS[area] && verb === 'read')
202
+ groups.sees.push(AREA_WORDS[area] as string)
203
+ else if (area && AREA_WORDS[area] && verb === 'write')
204
+ groups.changes.push(AREA_WORDS[area] as string)
205
+ }
206
+ if (options.screens)
207
+ groups.adds.push(options.screens === 1 ? 'a screen' : `${options.screens} screens`)
208
+ return groups
209
+ }
79
210
 
80
211
  export const isBundlePermission = (value: unknown): value is BundlePermission =>
81
212
  typeof value === 'string' && Object.hasOwn(BUNDLE_PERMISSIONS, value)
@@ -114,8 +245,14 @@ export function readPermissions(
114
245
  const declared: DeclaredPermission[] = []
115
246
  const problems: string[] = []
116
247
  for (const [permission, given] of Object.entries(value as Record<string, unknown>)) {
248
+ if (permission === 'actAs') {
249
+ problems.push(
250
+ `"actAs" is retired: ask for "${USER_DELEGATE}", which acts for the person using it across every area (\`crombolo extension migrate\` rewrites it)`,
251
+ )
252
+ continue
253
+ }
117
254
  if (NEVER_OFFERED.has(permission)) {
118
- problems.push(`"${permission}" is never offered: only an administrator changes users`)
255
+ problems.push(`"${permission}" is never offered: ${NEVER_OFFERED_WHY[permission]}`)
119
256
  continue
120
257
  }
121
258
  if (!isBundlePermission(permission)) {
@@ -141,6 +278,14 @@ export function readPermissions(
141
278
  declared.push({ permission, reason, origins: origins.filter(isOrigin) })
142
279
  } else declared.push({ permission, reason })
143
280
  }
281
+ const names = new Set(declared.map((entry) => entry.permission))
282
+ if (names.has(USER_DELEGATE)) {
283
+ const areas = AREA_PERMISSIONS.filter((permission) => names.has(permission))
284
+ if (areas.length > 0)
285
+ problems.push(
286
+ `"${USER_DELEGATE}" already reaches every area the person using it may: drop ${areas.map((p) => `"${p}"`).join(', ')}`,
287
+ )
288
+ }
144
289
  return problems.length > 0 ? { problem: problems.join('; ') } : { declared }
145
290
  }
146
291
 
@@ -150,7 +295,7 @@ export function describePermissions(permissions: readonly (string | DeclaredPerm
150
295
  allows: string
151
296
  reason: string | null
152
297
  origins?: string[]
153
- /** What the install says before it is granted: only `backoffice.code` has one (story 320). */
298
+ /** What the install says before it is granted: `backoffice.code` (story 320) and `user.delegate` (325). */
154
299
  warning?: string
155
300
  }[] {
156
301
  return permissions.map((entry) => {
@@ -161,6 +306,7 @@ export function describePermissions(permissions: readonly (string | DeclaredPerm
161
306
  reason: declared.reason,
162
307
  ...(declared.origins ? { origins: declared.origins } : {}),
163
308
  ...(declared.permission === BACKOFFICE_CODE ? { warning: BACKOFFICE_CODE_WARNING } : {}),
309
+ ...(declared.permission === USER_DELEGATE ? { warning: USER_DELEGATE_DETAIL } : {}),
164
310
  }
165
311
  })
166
312
  }
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Where installed extensions live (story 326): each in a root of its own,
3
+ * `extensions/<id>/`, with its own `package.json`, `bun.lock` and
4
+ * `node_modules`, and the site's record of them in `crombolo.extensions.json`.
5
+ * Nothing of an extension is a dependency of the site, so trying one never
6
+ * changes the site's lockfile, and removing one is deleting its root. The
7
+ * root's two files and the record are committed; its `node_modules` is not.
8
+ * docs/bundles.md, "The record and the roots".
9
+ */
10
+ import { createHash } from 'node:crypto'
11
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
12
+ import { join } from 'node:path'
13
+
14
+ /** The folder every extension's root sits in, at the site's root. */
15
+ export const ROOTS_DIR = 'extensions'
16
+
17
+ /** The site's record of what it has installed. */
18
+ export const RECORD_FILE = 'crombolo.extensions.json'
19
+
20
+ /** One installed extension, as the record keeps it. */
21
+ export interface RecordedExtension {
22
+ /** Its npm package name. */
23
+ name: string
24
+ /** The exact version installed. */
25
+ version: string
26
+ /** The tarball's integrity, as the registry or the kept file gives it; absent for a link. */
27
+ integrity?: string
28
+ /** A hash of what it was granted, so an apply can tell a grant that no longer covers it. */
29
+ grant?: string
30
+ /** Installed from a path or a workspace on a developer's machine, outside production only. */
31
+ linked?: boolean
32
+ }
33
+
34
+ /** By extension id, sorted, as the file holds it. */
35
+ export type ExtensionRecord = Record<string, RecordedExtension>
36
+
37
+ export const rootOf = (siteDir: string, id: string): string => join(siteDir, ROOTS_DIR, id)
38
+
39
+ /** Where an extension's package sits in its root. */
40
+ export const packageInRoot = (siteDir: string, id: string, name: string): string =>
41
+ join(rootOf(siteDir, id), 'node_modules', name)
42
+
43
+ /** The site's record, or an empty one when there is none or it does not read. */
44
+ export function readRecord(siteDir: string): ExtensionRecord {
45
+ try {
46
+ const parsed = JSON.parse(readFileSync(join(siteDir, RECORD_FILE), 'utf8')) as unknown
47
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {}
48
+ const out: ExtensionRecord = {}
49
+ for (const [id, line] of Object.entries(parsed as Record<string, unknown>)) {
50
+ const entry = line as Partial<RecordedExtension> | null
51
+ if (entry && typeof entry.name === 'string' && typeof entry.version === 'string')
52
+ out[id] = {
53
+ name: entry.name,
54
+ version: entry.version,
55
+ ...(typeof entry.integrity === 'string' ? { integrity: entry.integrity } : {}),
56
+ ...(typeof entry.grant === 'string' ? { grant: entry.grant } : {}),
57
+ ...(entry.linked === true ? { linked: true } : {}),
58
+ }
59
+ }
60
+ return out
61
+ } catch {
62
+ return {}
63
+ }
64
+ }
65
+
66
+ /** Writes the record sorted by id, so a change to it is a change to one line. */
67
+ export function writeRecord(siteDir: string, record: ExtensionRecord): void {
68
+ const sorted = Object.fromEntries(Object.entries(record).sort(([a], [b]) => a.localeCompare(b)))
69
+ writeFileSync(join(siteDir, RECORD_FILE), `${JSON.stringify(sorted, null, 2)}\n`)
70
+ }
71
+
72
+ /** Records one extension, replacing what was there for it. */
73
+ export function recordExtension(siteDir: string, id: string, line: RecordedExtension): void {
74
+ writeRecord(siteDir, { ...readRecord(siteDir), [id]: line })
75
+ }
76
+
77
+ /** Takes one extension out of the record. */
78
+ export function forgetExtension(siteDir: string, id: string): void {
79
+ const { [id]: _, ...rest } = readRecord(siteDir)
80
+ writeRecord(siteDir, rest)
81
+ }
82
+
83
+ /** A root ready for `bun add`: its folder and a `package.json` that is nobody's package. */
84
+ export function prepareRoot(siteDir: string, id: string): string {
85
+ const root = rootOf(siteDir, id)
86
+ mkdirSync(root, { recursive: true })
87
+ const manifest = join(root, 'package.json')
88
+ if (!existsSync(manifest))
89
+ writeFileSync(
90
+ manifest,
91
+ `${JSON.stringify({ name: `${id}-root`, private: true, dependencies: {} }, null, 2)}\n`,
92
+ )
93
+ return root
94
+ }
95
+
96
+ /** Why the record and the roots disagree: a root with no line, or a line with no root. Pure but for reading the folder. */
97
+ export function recordProblems(siteDir: string, record = readRecord(siteDir)): string[] {
98
+ const problems: string[] = []
99
+ const roots = existsSync(join(siteDir, ROOTS_DIR))
100
+ ? readdirSync(join(siteDir, ROOTS_DIR), { withFileTypes: true })
101
+ .filter((entry) => entry.isDirectory())
102
+ .map((entry) => entry.name)
103
+ : []
104
+ for (const id of roots)
105
+ if (!record[id])
106
+ problems.push(
107
+ `${ROOTS_DIR}/${id}/ is an extension's root that ${RECORD_FILE} does not name: install it again, or delete the folder`,
108
+ )
109
+ for (const [id, line] of Object.entries(record))
110
+ if (!existsSync(join(packageInRoot(siteDir, id, line.name), 'package.json')))
111
+ problems.push(
112
+ `${RECORD_FILE} names ${line.name}@${line.version} as "${id}", which is not installed in ${ROOTS_DIR}/${id}/: run \`bun install --frozen-lockfile\` there`,
113
+ )
114
+ return problems
115
+ }
116
+
117
+ /** A stable hash of what was granted: permissions and origins, in any order. Pure. */
118
+ export function grantHashOf(
119
+ permissions: readonly string[],
120
+ origins: readonly string[] = [],
121
+ ): string {
122
+ const text = JSON.stringify([[...permissions].sort(), [...origins].sort()])
123
+ return `sha256-${createHash('sha256').update(text).digest('hex').slice(0, 32)}`
124
+ }
125
+
126
+ /** What a dependency of the site that is an extension is told, since this release does not run it. */
127
+ export const INSTALLED_AS_DEPENDENCY =
128
+ 'it is installed as a dependency of the site, which this release no longer runs: remove it from package.json and install it again with `crombolo extension install`, so it has a root of its own'
package/src/extensions.ts CHANGED
@@ -19,6 +19,7 @@ import {
19
19
  readBundlePackage,
20
20
  } from './bundle-package.ts'
21
21
  import type { PackageManifest, PackageManifestImportmap } from './manifests.ts'
22
+ import { PLUGIN_PATH_PLACEHOLDER } from './paths.ts'
22
23
 
23
24
  /** Where an installed bundle's assets are served from. */
24
25
  export const EXTENSION_PATH = '/bundles'
@@ -97,6 +98,28 @@ function rewriteImportmap(
97
98
  return Object.keys(scopes).length > 0 ? { imports, scopes } : { imports }
98
99
  }
99
100
 
101
+ /** The back office's own element that draws every described screen (story 323). */
102
+ export const SCREEN_ELEMENT = `${PLUGIN_PATH_PLACEHOLDER}/extension-screen.js`
103
+
104
+ /**
105
+ * An entry that names a screen, as the back office loads it: the host's element,
106
+ * told which extension and screen to ask for. Any other entry is unchanged.
107
+ */
108
+ export function describedScreen(entry: unknown, bundleId: string): unknown {
109
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return entry
110
+ const { screen, ...rest } = entry as Record<string, unknown>
111
+ if (typeof screen !== 'string') return entry
112
+ const meta = (rest.meta && typeof rest.meta === 'object' ? rest.meta : {}) as Record<
113
+ string,
114
+ unknown
115
+ >
116
+ return {
117
+ ...rest,
118
+ element: SCREEN_ELEMENT,
119
+ meta: { ...meta, cromboloScreen: { bundle: bundleId, screen } },
120
+ }
121
+ }
122
+
100
123
  /** A bundle's backoffice half, or undefined when it declares no extensions. */
101
124
  export function extensionOf(bundle: BundlePackage): InstalledExtension | undefined {
102
125
  const field = bundle.field
@@ -115,7 +138,7 @@ export function extensionOf(bundle: BundlePackage): InstalledExtension | undefin
115
138
  allowTelemetry: field.allowTelemetry ?? false,
116
139
  // Each extension names its bundle, so Settings can group a bundle's cards and link to it.
117
140
  extensions: (field.extensions ?? []).map((extension) => {
118
- const rewritten = rewriteAssets(extension, packageName)
141
+ const rewritten = rewriteAssets(describedScreen(extension, bundle.id), packageName)
119
142
  return rewritten && typeof rewritten === 'object'
120
143
  ? { ...rewritten, cromboloBundle: { name: bundle.name, packageName } }
121
144
  : rewritten
package/src/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export * from './bundle-package.ts'
2
2
  export * from './bundle-permissions.ts'
3
3
  export * from './content-security.ts'
4
+ export * from './extension-roots.ts'
4
5
  export * from './extensions.ts'
5
6
  export * from './graphics.ts'
6
7
  export * from './login-assets.ts'
package/src/manifests.ts CHANGED
@@ -93,7 +93,18 @@ export function collectManifests(
93
93
  const all = [...discoverManifests(paths.vendorDir), ...frameworkManifests(paths)].filter(
94
94
  (manifest) => !omit.has(manifest.id ?? ''),
95
95
  )
96
- all.push(...extensions.map((extension) => extension.manifest))
96
+ // A described screen is drawn by the back office's own element, wherever it is mounted.
97
+ all.push(
98
+ ...extensions.map(
99
+ (extension) =>
100
+ JSON.parse(
101
+ JSON.stringify(extension.manifest).replaceAll(
102
+ `"${PLUGIN_PATH_PLACEHOLDER}/`,
103
+ `"${paths.pluginPath}/`,
104
+ ),
105
+ ) as PackageManifest,
106
+ ),
107
+ )
97
108
 
98
109
  const imports: Record<string, string> = {}
99
110
  const scopes: Record<string, Record<string, string>> = {}