@cosmicdrift/kumiko-bundled-features 0.420.0 → 0.422.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.
@@ -134,3 +134,14 @@ export declare function seedBootstrapAdmin(db: DbConnection, options: SeedAdminO
134
134
  } | {
135
135
  skipped: "has-password" | "tenant-has-members";
136
136
  }>;
137
+ /**
138
+ * Boot top-up for the bootstrap owner: adds the roles the owner's existing membership in the tenant
139
+ * lacks. Only a membership the system user created and last wrote is touched, so a human role change since then is not reverted at boot; the mail is unique per account, so the account is the owner named in the env.
140
+ */
141
+ export declare function ensureBootstrapAdminRoles(db: DbConnection, options: {
142
+ readonly email: string;
143
+ readonly tenantId: TenantId;
144
+ readonly roles: readonly string[];
145
+ }): Promise<{
146
+ readonly added: readonly string[];
147
+ }>;
@@ -13,14 +13,14 @@
13
13
  // sub-paths themselves.
14
14
  import { configuredBlindIndexKey, configuredPiiSubjectKms, decryptPiiFieldValues, } from "@cosmicdrift/kumiko-framework/crypto";
15
15
  import { fetchOne, selectMany } from "@cosmicdrift/kumiko-framework/db";
16
- import { createSystemUser, SYSTEM_TENANT_ID, } from "@cosmicdrift/kumiko-framework/engine";
16
+ import { createSystemUser, SYSTEM_TENANT_ID, SYSTEM_USER_ID, } from "@cosmicdrift/kumiko-framework/engine";
17
17
  import { ConflictError } from "@cosmicdrift/kumiko-framework/errors";
18
18
  import { createFallbackLogger } from "@cosmicdrift/kumiko-framework/logging";
19
19
  import { hashPassword, verifyPassword } from "../shared/index.js";
20
20
  // kumiko-lint-ignore cross-feature-import bootstrap admin seed checks whether the tenant already has members
21
21
  import { tenantMembershipsTable } from "../tenant/membership-table.js";
22
22
  // kumiko-lint-ignore cross-feature-import auth-tests need user+tenant seed-helpers
23
- import { seedTenant, seedTenantMembership } from "../tenant/seeding.js";
23
+ import { addTenantMembershipRoles, seedTenant, seedTenantMembership, } from "../tenant/seeding.js";
24
24
  // kumiko-lint-ignore cross-feature-import signup create-only guard reads the user projection by email
25
25
  import { USER_STATUS, userTable } from "../user/schema/user.js";
26
26
  // kumiko-lint-ignore cross-feature-import auth-tests need user+tenant seed-helpers
@@ -350,3 +350,18 @@ export async function seedBootstrapAdmin(db, options) {
350
350
  }
351
351
  return seeded;
352
352
  }
353
+ /**
354
+ * Boot top-up for the bootstrap owner: adds the roles the owner's existing membership in the tenant
355
+ * lacks. Only a membership the system user created and last wrote is touched, so a human role change since then is not reverted at boot; the mail is unique per account, so the account is the owner named in the env.
356
+ */
357
+ export async function ensureBootstrapAdminRoles(db, options) {
358
+ const owner = await findExistingUserRowForEmail(db, options.email);
359
+ if (typeof owner?.["id"] !== "string")
360
+ return { added: [] };
361
+ return addTenantMembershipRoles(db, {
362
+ userId: owner["id"],
363
+ tenantId: options.tenantId,
364
+ roles: options.roles,
365
+ onlyIfInsertedBy: SYSTEM_USER_ID,
366
+ });
367
+ }
@@ -1,4 +1,14 @@
1
1
  import type { TemplateVariables } from "@cosmicdrift/kumiko-framework/engine";
2
+ export type DocumentImageEntry = {
3
+ readonly fileRefId: string;
4
+ readonly caption?: string;
5
+ };
6
+ export type DocumentImageValue = string | DocumentImageEntry;
7
+ export type DocumentRecordImage = {
8
+ readonly src: string;
9
+ readonly caption?: string;
10
+ };
11
+ export declare function documentImageEntriesOf(value: unknown): readonly DocumentImageEntry[];
2
12
  export type CompileDocumentBodyOptions = {
3
13
  readonly resourceSrc?: (key: string) => string | undefined;
4
14
  readonly resourceImageMaxWidthPx?: number;
@@ -9,7 +19,7 @@ export type CompileDocumentBodyOptions = {
9
19
  readonly buttonInlineStyle?: string;
10
20
  readonly headingAsInlineStyle?: boolean;
11
21
  readonly stepsColor?: string;
12
- readonly recordImagesSrc?: (variable: string) => readonly string[];
22
+ readonly recordImagesSrc?: (variable: string) => readonly DocumentRecordImage[];
13
23
  readonly recordImagesPlaceholder?: boolean;
14
24
  };
15
25
  export declare function collectDocumentResourceKeys(html: string): readonly string[];
@@ -1,8 +1,9 @@
1
- import { isOneOf } from "@cosmicdrift/kumiko-types/type-guards";
1
+ import { isOneOf, isPlainObject } from "@cosmicdrift/kumiko-types/type-guards";
2
2
  import { isResourceImageContentType } from "../shared/index.js";
3
3
  import { appendStyle, applyDocumentPrintStyles } from "./compile-document-styles.js";
4
4
  import { rewriteStepsBlock } from "./compile-steps-block.js";
5
5
  import { conditionScopeElement, withParsedDocument } from "./document-sanitizer.js";
6
+ import { readDocumentImageColumns } from "./web/document-images.js";
6
7
  import { DOCUMENT_CONDITION_ATTRIBUTE, DOCUMENT_TEXT_ALIGNMENTS, isAllowedDocumentUrlHref, isDocumentPlaceholderHref, isDocumentReferenceName, isDocumentResourceKey, readDocumentDateStyle, } from "./web/document-schema.js";
7
8
  // Private-use characters mark where a Handlebars expression goes. Author text
8
9
  // is scrubbed of them first and every `{`/`}` is entity-encoded before the
@@ -161,6 +162,26 @@ function stripActiveContent(element) {
161
162
  function neutralizeBraces(html) {
162
163
  return html.replace(/[{}]/g, (brace) => (brace === "{" ? "&#123;" : "&#125;"));
163
164
  }
165
+ const MAX_IMAGE_CAPTION_LENGTH = 200;
166
+ const DEFAULT_IMAGE_COLUMNS = "2";
167
+ function imageEntryOf(value) {
168
+ if (typeof value === "string")
169
+ return { fileRefId: value };
170
+ if (!isPlainObject(value) || typeof value["fileRefId"] !== "string")
171
+ return null;
172
+ const caption = value["caption"];
173
+ return typeof caption === "string" && caption.trim() !== ""
174
+ ? { fileRefId: value["fileRefId"], caption }
175
+ : { fileRefId: value["fileRefId"] };
176
+ }
177
+ // Invalid entries drop silently; a single string value stays valid.
178
+ export function documentImageEntriesOf(value) {
179
+ const entries = Array.isArray(value) ? value : [value];
180
+ return entries.flatMap((entry) => {
181
+ const parsed = imageEntryOf(entry);
182
+ return parsed === null ? [] : [parsed];
183
+ });
184
+ }
164
185
  const IMAGES_PLACEHOLDER_STYLE = "height:96px;margin:8px 0;border-radius:4px;background:#e5e7eb";
165
186
  const MAIL_BUTTON_STYLE = "display:inline-block;padding:10px 20px;border-radius:6px;background-color:#1f5468;color:#ffffff;font-weight:600;text-decoration:none";
166
187
  const MAIL_TABLE_STYLE = "width:100%;border-collapse:collapse";
@@ -200,19 +221,35 @@ function rewriteImagesBlock(element, state, options) {
200
221
  return;
201
222
  }
202
223
  const document = element.ownerDocument;
224
+ const columns = readDocumentImageColumns(element.getAttribute("data-image-columns"));
203
225
  element.removeAttribute("data-images");
226
+ element.removeAttribute("data-image-columns");
204
227
  if (options.recordImagesPlaceholder === true) {
205
228
  element.setAttribute("class", "kumiko-doc-image-placeholder");
206
- element.setAttribute("style", IMAGES_PLACEHOLDER_STYLE);
229
+ const widthStyle = `;width:${Math.floor(100 / Number(columns ?? DEFAULT_IMAGE_COLUMNS))}%`;
230
+ element.setAttribute("style", `${IMAGES_PLACEHOLDER_STYLE}${widthStyle}`);
207
231
  // skip: preview and drafts never resolve record images
208
232
  return;
209
233
  }
210
234
  element.setAttribute("class", "kumiko-doc-images");
211
- for (const src of options.recordImagesSrc?.(name) ?? []) {
235
+ if (columns !== null) {
236
+ element.setAttribute("style", `grid-template-columns:repeat(${columns},1fr)`);
237
+ }
238
+ for (const { src, caption } of options.recordImagesSrc?.(name) ?? []) {
212
239
  const image = document.createElement("img");
213
240
  image.setAttribute("src", src);
214
- image.setAttribute("alt", "");
215
- element.append(image);
241
+ const text = caption?.trim().slice(0, MAX_IMAGE_CAPTION_LENGTH) ?? "";
242
+ image.setAttribute("alt", text);
243
+ if (text === "") {
244
+ element.append(image);
245
+ continue;
246
+ }
247
+ const figure = document.createElement("figure");
248
+ figure.setAttribute("class", "kumiko-doc-image");
249
+ const figcaption = document.createElement("figcaption");
250
+ figcaption.append(document.createTextNode(text));
251
+ figure.append(image, figcaption);
252
+ element.append(figure);
216
253
  }
217
254
  }
218
255
  export function toResourceDataUri(contentType, bytes) {
@@ -1,6 +1,6 @@
1
1
  import type { Element as ScanElement } from "happy-dom";
2
2
  export declare const IMAGES_BLOCK_SELECTOR = "div[data-images]";
3
- export declare const PRINT_STYLE_SELECTORS: readonly ["div[data-frame]", "span[data-text-style]", "[data-line-height]", "[data-space-before]", "[data-space-after]", "table[data-borders]", "table[data-cell-padding-mm]", "table[data-table-width-mm]", "table[data-table-align]", "tr[data-line-above]", "tr[data-line-below]", "[data-background]", "[data-colwidth]", "img[data-bleed]", "img[data-width-mm]", "img[data-align]", "hr[data-color]", "hr[data-weight-pt]"];
3
+ export declare const PRINT_STYLE_SELECTORS: readonly ["div[data-frame]", "span[data-text-style]", "[data-line-height]", "[data-space-before]", "[data-space-after]", "table[data-borders]", "table[data-cell-padding-mm]", "table[data-table-width-mm]", "table[data-table-align]", "tr[data-line-above]", "tr[data-line-below]", "[data-background]", "[data-colwidth]", "div[data-image-columns]", "img[data-bleed]", "img[data-width-mm]", "img[data-align]", "hr[data-color]", "hr[data-weight-pt]"];
4
4
  export type PrintOnlyFeatures = {
5
5
  readonly hasImagesBlock: boolean;
6
6
  readonly printStyleSelectors: readonly string[];
@@ -15,6 +15,7 @@ export const PRINT_STYLE_SELECTORS = [
15
15
  "tr[data-line-below]",
16
16
  "[data-background]",
17
17
  "[data-colwidth]",
18
+ "div[data-image-columns]",
18
19
  "img[data-bleed]",
19
20
  "img[data-width-mm]",
20
21
  "img[data-align]",
@@ -1,6 +1,6 @@
1
1
  export { isResourceImageContentType } from "../shared/index.ts";
2
2
  export { createTemplateResolverApi, type ResolveRequest, requireTemplateResolver, TemplateNotFoundError, type TemplateResolverApi, type TemplateResource, } from "./api.ts";
3
- export { type CompileDocumentBodyOptions, collectDocumentImageVariables, collectDocumentResourceKeys, compileDocumentBodyToHandlebars, toResourceDataUri, } from "./compile-document-body.ts";
3
+ export { type CompileDocumentBodyOptions, collectDocumentImageVariables, collectDocumentResourceKeys, compileDocumentBodyToHandlebars, type DocumentImageEntry, type DocumentImageValue, type DocumentRecordImage, documentImageEntriesOf, toResourceDataUri, } from "./compile-document-body.ts";
4
4
  export { flattenAddressSenderLine, flattenFramesForPreview, readTopLevelFrames, } from "./document-frames.ts";
5
5
  export { type DocumentViolation, type DocumentViolationCode, documentViolationsToFieldIssues, flattenParagraphsToLineBreaks, type SanitizeBodyResult, type SanitizeHtmlResult, sanitizeDocumentHtml, sanitizeTemplateBody, } from "./document-sanitizer.ts";
6
6
  export { createTemplateResolverFeature, type TemplateResolverOptions } from "./feature.ts";
@@ -1,6 +1,6 @@
1
1
  export { isResourceImageContentType } from "../shared/index.js";
2
2
  export { createTemplateResolverApi, requireTemplateResolver, TemplateNotFoundError, } from "./api.js";
3
- export { collectDocumentImageVariables, collectDocumentResourceKeys, compileDocumentBodyToHandlebars, toResourceDataUri, } from "./compile-document-body.js";
3
+ export { collectDocumentImageVariables, collectDocumentResourceKeys, compileDocumentBodyToHandlebars, documentImageEntriesOf, toResourceDataUri, } from "./compile-document-body.js";
4
4
  export { flattenAddressSenderLine, flattenFramesForPreview, readTopLevelFrames, } from "./document-frames.js";
5
5
  export { documentViolationsToFieldIssues, flattenParagraphsToLineBreaks, sanitizeDocumentHtml, sanitizeTemplateBody, } from "./document-sanitizer.js";
6
6
  export { createTemplateResolverFeature } from "./feature.js";
@@ -1,2 +1,5 @@
1
1
  import { Node } from "@tiptap/core";
2
+ export declare const DOCUMENT_IMAGE_COLUMNS: readonly ["1", "2", "3"];
3
+ export type DocumentImageColumns = (typeof DOCUMENT_IMAGE_COLUMNS)[number];
4
+ export declare function readDocumentImageColumns(value: unknown): DocumentImageColumns | null;
2
5
  export declare function createDocumentImagesNode(isReferenceName: (value: string) => boolean): Node<any, any>;
@@ -1,27 +1,44 @@
1
1
  // The record's photos: a block bound to an `images` variable whose FileRef ids the
2
2
  // app passes at render time. Universal like document-schema.ts.
3
+ import { isOneOf } from "@cosmicdrift/kumiko-types/type-guards";
3
4
  import { Node } from "@tiptap/core";
4
- import { attributeParseRule } from "./tiptap-attribute-parse-rule.js";
5
+ export const DOCUMENT_IMAGE_COLUMNS = ["1", "2", "3"];
6
+ export function readDocumentImageColumns(value) {
7
+ return isOneOf(DOCUMENT_IMAGE_COLUMNS, value) ? value : null;
8
+ }
5
9
  export function createDocumentImagesNode(isReferenceName) {
6
10
  return Node.create({
7
11
  name: "images",
8
12
  group: "block",
9
13
  atom: true,
10
14
  addAttributes() {
11
- return { variable: { default: null } };
15
+ return { variable: { default: null }, columns: { default: null } };
12
16
  },
13
17
  parseHTML() {
14
18
  return [
15
- attributeParseRule({
19
+ {
16
20
  tag: "div[data-images]",
17
- attribute: "data-images",
18
- key: "variable",
19
- isValid: isReferenceName,
20
- }),
21
+ getAttrs: (element) => {
22
+ const variable = element.getAttribute("data-images");
23
+ if (variable === null || !isReferenceName(variable))
24
+ return false;
25
+ return {
26
+ variable,
27
+ columns: readDocumentImageColumns(element.getAttribute("data-image-columns")),
28
+ };
29
+ },
30
+ },
21
31
  ];
22
32
  },
23
33
  renderHTML({ node }) {
24
- return ["div", { "data-images": node.attrs["variable"] }];
34
+ const columns = readDocumentImageColumns(node.attrs["columns"]);
35
+ return [
36
+ "div",
37
+ {
38
+ "data-images": node.attrs["variable"],
39
+ ...(columns !== null && { "data-image-columns": columns }),
40
+ },
41
+ ];
25
42
  },
26
43
  });
27
44
  }
@@ -62,3 +62,17 @@ export declare function seedTenantMembership(db: DbRunner, options: SeedTenantMe
62
62
  id: string;
63
63
  rowMissing?: true;
64
64
  }>;
65
+ /**
66
+ * Add-only top-up for an EXISTING membership: roles the membership lacks are appended through the
67
+ * event-store executor (one update event), nothing is removed. No event when all roles are present;
68
+ * no membership is created.
69
+ */
70
+ export declare function addTenantMembershipRoles(db: DbRunner, options: {
71
+ readonly userId: string;
72
+ readonly tenantId: TenantId;
73
+ readonly roles: readonly string[];
74
+ /** Only touch a membership this id created and last wrote (boot seeds pass SYSTEM_USER_ID), so a human role change since then is not reverted. */
75
+ readonly onlyIfInsertedBy?: string;
76
+ }): Promise<{
77
+ readonly added: readonly string[];
78
+ }>;
@@ -31,6 +31,7 @@ import { createEventStoreExecutor, createTenantDb, fetchOne, } from "@cosmicdrif
31
31
  import { attachOutsideTransaction, createSystemUser, HookPhases, SYSTEM_TENANT_ID, } from "@cosmicdrift/kumiko-framework/engine";
32
32
  import { getUnscopedAggregateStreamMaxVersion } from "@cosmicdrift/kumiko-framework/event-store";
33
33
  import { createDeferringNotify, createLifecycleHooks, } from "@cosmicdrift/kumiko-framework/pipeline";
34
+ import { parseRoles } from "@cosmicdrift/kumiko-framework/utils";
34
35
  import { assertAssignableMembershipRoles } from "./membership-roles.js";
35
36
  import { findLiveMembershipStreamId } from "./membership-stream-history.js";
36
37
  import { tenantMembershipEntity, tenantMembershipsTable } from "./membership-table.js";
@@ -256,3 +257,46 @@ function extractMembershipId(data) {
256
257
  }
257
258
  throw new Error(`seedTenantMembership: executor.create returned no string id (got ${JSON.stringify(data)})`);
258
259
  }
260
+ // ponytail: checks creator and last writer only; a human demotion followed by a system write
261
+ // (invite acceptance) passes. Scan the membership's event stream for non-system actors if that matters.
262
+ function wasOnlyWrittenBy(row, actorId) {
263
+ return (row.insertedById === actorId && (row.modifiedById === null || row.modifiedById === actorId));
264
+ }
265
+ /**
266
+ * Add-only top-up for an EXISTING membership: roles the membership lacks are appended through the
267
+ * event-store executor (one update event), nothing is removed. No event when all roles are present;
268
+ * no membership is created.
269
+ */
270
+ export async function addTenantMembershipRoles(db, options) {
271
+ assertAssignableMembershipRoles(options.roles);
272
+ // One re-read on version_conflict: a concurrent boot (second pod) may have added the same roles.
273
+ for (let attempt = 0; attempt < 2; attempt++) {
274
+ const existing = await fetchOne(db, tenantMembershipsTable, { userId: options.userId, tenantId: options.tenantId });
275
+ if (!existing)
276
+ return { added: [] };
277
+ if (options.onlyIfInsertedBy !== undefined &&
278
+ !wasOnlyWrittenBy(existing, options.onlyIfInsertedBy)) {
279
+ return { added: [] };
280
+ }
281
+ const currentRoles = parseRoles(existing.roles);
282
+ const added = options.roles.filter((role) => !currentRoles.includes(role));
283
+ if (added.length === 0)
284
+ return { added };
285
+ const result = await executor.update({
286
+ id: existing.id,
287
+ version: existing.version,
288
+ changes: { roles: JSON.stringify([...currentRoles, ...added]) },
289
+ }, createSystemUser(options.tenantId), createTenantDb({
290
+ db,
291
+ tenantId: options.tenantId,
292
+ mode: "system",
293
+ reason: "boot seed tops up the owner's membership roles in the seeded tenant",
294
+ }));
295
+ if (result.isSuccess)
296
+ return { added };
297
+ if (result.error.code === "version_conflict" && attempt === 0)
298
+ continue;
299
+ throw new Error(`addTenantMembershipRoles failed: ${result.error.code} — ${JSON.stringify(result.error.details ?? {})}`);
300
+ }
301
+ return { added: [] };
302
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cosmicdrift/kumiko-bundled-features",
3
- "version": "0.420.0",
3
+ "version": "0.422.0",
4
4
  "description": "Built-in features — tenant, user, auth, delivery. The stuff you'd rewrite anyway, already typed.",
5
5
  "license": "MIT",
6
6
  "author": "Marc Frost <marc@cosmicdriftgamestudio.com>",
@@ -646,9 +646,9 @@
646
646
  }
647
647
  },
648
648
  "dependencies": {
649
- "@cosmicdrift/kumiko-framework": "0.420.0",
650
- "@cosmicdrift/kumiko-renderer": "0.420.0",
651
- "@cosmicdrift/kumiko-types": "0.420.0",
649
+ "@cosmicdrift/kumiko-framework": "0.422.0",
650
+ "@cosmicdrift/kumiko-renderer": "0.422.0",
651
+ "@cosmicdrift/kumiko-types": "0.422.0",
652
652
  "@fontsource/arimo": "^5.3.0",
653
653
  "@fontsource/caladea": "^5.3.0",
654
654
  "@fontsource/carlito": "^5.3.0",
@@ -1323,19 +1323,19 @@
1323
1323
  "LICENSE"
1324
1324
  ],
1325
1325
  "devDependencies": {
1326
- "@cosmicdrift/kumiko-locale-de": "0.420.0",
1327
- "@cosmicdrift/kumiko-locale-es": "0.420.0",
1328
- "@cosmicdrift/kumiko-locale-fr": "0.420.0",
1329
- "@cosmicdrift/kumiko-locale-it": "0.420.0",
1330
- "@cosmicdrift/kumiko-renderer-mail-html": "0.420.0",
1331
- "@cosmicdrift/kumiko-testing": "0.420.0",
1326
+ "@cosmicdrift/kumiko-locale-de": "0.422.0",
1327
+ "@cosmicdrift/kumiko-locale-es": "0.422.0",
1328
+ "@cosmicdrift/kumiko-locale-fr": "0.422.0",
1329
+ "@cosmicdrift/kumiko-locale-it": "0.422.0",
1330
+ "@cosmicdrift/kumiko-renderer-mail-html": "0.422.0",
1331
+ "@cosmicdrift/kumiko-testing": "0.422.0",
1332
1332
  "@testing-library/user-event": "^14.6.8",
1333
1333
  "@types/sanitize-html": "^2.16.2",
1334
1334
  "jsqr": "^1.4.0",
1335
1335
  "unpdf": "^1.9.1"
1336
1336
  },
1337
1337
  "peerDependencies": {
1338
- "@cosmicdrift/kumiko-testing": "0.420.0"
1338
+ "@cosmicdrift/kumiko-testing": "0.422.0"
1339
1339
  },
1340
1340
  "peerDependenciesMeta": {
1341
1341
  "@cosmicdrift/kumiko-testing": {
@@ -1,4 +1,10 @@
1
1
  [
2
+ {
3
+ "version": "0.422.0",
4
+ "type": "improvement",
5
+ "title": "PDF image captions, image columns and page-break rules",
6
+ "detail": "Entries of an `images` variable can carry a caption (`{ fileRefId, caption }`), printed under the image as a figcaption. The Images block accepts `data-image-columns` 1, 2 or 3. The print CSS keeps headings with the next paragraph and avoids splitting paragraphs, list items, table rows and figures across pages; tables of up to 8 rows stay whole."
7
+ },
2
8
  {
3
9
  "version": "0.420.0",
4
10
  "type": "improvement",