@feltdb/feltkit 0.3.30 → 0.3.32

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 (157) hide show
  1. package/dist/app.d.ts +67 -11
  2. package/dist/app.js +58 -2
  3. package/dist/app.js.map +1 -1
  4. package/dist/appboundry/build.js +2 -0
  5. package/dist/appboundry/build.js.map +1 -1
  6. package/dist/appboundry/guest.js +23 -1
  7. package/dist/appboundry/guest.js.map +1 -1
  8. package/dist/authorize.d.ts +24 -3
  9. package/dist/authorize.js.map +1 -1
  10. package/dist/broker/assertion.d.ts +68 -0
  11. package/dist/broker/assertion.js +104 -0
  12. package/dist/broker/assertion.js.map +1 -0
  13. package/dist/broker/keys.d.ts +9 -0
  14. package/dist/broker/keys.js +47 -0
  15. package/dist/broker/keys.js.map +1 -0
  16. package/dist/broker/server.d.ts +54 -0
  17. package/dist/broker/server.js +305 -0
  18. package/dist/broker/server.js.map +1 -0
  19. package/dist/cli/broker.d.ts +11 -0
  20. package/dist/cli/broker.js +72 -0
  21. package/dist/cli/broker.js.map +1 -0
  22. package/dist/cli/deploy.js +6 -0
  23. package/dist/cli/deploy.js.map +1 -1
  24. package/dist/cli/main.js +123 -0
  25. package/dist/cli/main.js.map +1 -1
  26. package/dist/client/index.d.ts +8 -2
  27. package/dist/client/index.js +45 -1
  28. package/dist/client/index.js.map +1 -1
  29. package/dist/docs.d.ts +1 -1
  30. package/dist/docs.js +3 -0
  31. package/dist/docs.js.map +1 -1
  32. package/dist/extension/build.d.ts +50 -0
  33. package/dist/extension/build.js +205 -0
  34. package/dist/extension/build.js.map +1 -0
  35. package/dist/extension/client-shim.d.ts +7 -0
  36. package/dist/extension/client-shim.js +13 -0
  37. package/dist/extension/client-shim.js.map +1 -0
  38. package/dist/extension/connect-ui.d.ts +24 -0
  39. package/dist/extension/connect-ui.js +67 -0
  40. package/dist/extension/connect-ui.js.map +1 -0
  41. package/dist/extension/connection.d.ts +109 -0
  42. package/dist/extension/connection.js +190 -0
  43. package/dist/extension/connection.js.map +1 -0
  44. package/dist/extension/host-core.d.ts +36 -0
  45. package/dist/extension/host-core.js +50 -0
  46. package/dist/extension/host-core.js.map +1 -0
  47. package/dist/extension/host.d.ts +1 -0
  48. package/dist/extension/host.js +8 -0
  49. package/dist/extension/host.js.map +1 -0
  50. package/dist/extension/icons.d.ts +13 -0
  51. package/dist/extension/icons.js +75 -0
  52. package/dist/extension/icons.js.map +1 -0
  53. package/dist/extension/identity.d.ts +40 -0
  54. package/dist/extension/identity.js +110 -0
  55. package/dist/extension/identity.js.map +1 -0
  56. package/dist/extension/options.d.ts +1 -0
  57. package/dist/extension/options.js +57 -0
  58. package/dist/extension/options.js.map +1 -0
  59. package/dist/extension/service-worker.d.ts +1 -0
  60. package/dist/extension/service-worker.js +38 -0
  61. package/dist/extension/service-worker.js.map +1 -0
  62. package/dist/extension/validate.d.ts +7 -0
  63. package/dist/extension/validate.js +143 -0
  64. package/dist/extension/validate.js.map +1 -0
  65. package/dist/extension/zip.d.ts +7 -0
  66. package/dist/extension/zip.js +94 -0
  67. package/dist/extension/zip.js.map +1 -0
  68. package/dist/index.d.ts +6 -2
  69. package/dist/index.js +1 -0
  70. package/dist/index.js.map +1 -1
  71. package/dist/policy.d.ts +179 -0
  72. package/dist/policy.js +311 -0
  73. package/dist/policy.js.map +1 -0
  74. package/dist/runtime/activity.d.ts +16 -0
  75. package/dist/runtime/activity.js.map +1 -1
  76. package/dist/runtime/application-authority.d.ts +22 -3
  77. package/dist/runtime/application-authority.js +94 -20
  78. package/dist/runtime/application-authority.js.map +1 -1
  79. package/dist/runtime/assemble.d.ts +13 -0
  80. package/dist/runtime/assemble.js +29 -1
  81. package/dist/runtime/assemble.js.map +1 -1
  82. package/dist/runtime/authority-contract.d.ts +55 -0
  83. package/dist/runtime/authority-contract.js +60 -0
  84. package/dist/runtime/authority-contract.js.map +1 -0
  85. package/dist/runtime/content.d.ts +50 -0
  86. package/dist/runtime/content.js +98 -1
  87. package/dist/runtime/content.js.map +1 -1
  88. package/dist/runtime/context.d.ts +86 -11
  89. package/dist/runtime/contract.js +11 -2
  90. package/dist/runtime/contract.js.map +1 -1
  91. package/dist/runtime/data.d.ts +25 -0
  92. package/dist/runtime/data.js +92 -8
  93. package/dist/runtime/data.js.map +1 -1
  94. package/dist/runtime/image-variants.d.ts +48 -0
  95. package/dist/runtime/image-variants.js +295 -0
  96. package/dist/runtime/image-variants.js.map +1 -0
  97. package/dist/runtime/integrations.d.ts +2 -0
  98. package/dist/runtime/integrations.js +10 -7
  99. package/dist/runtime/integrations.js.map +1 -1
  100. package/dist/runtime/invocations.d.ts +3 -0
  101. package/dist/runtime/invocations.js +1 -1
  102. package/dist/runtime/invocations.js.map +1 -1
  103. package/dist/runtime/live.d.ts +10 -7
  104. package/dist/runtime/live.js +24 -12
  105. package/dist/runtime/live.js.map +1 -1
  106. package/dist/runtime/local-authority.d.ts +80 -5
  107. package/dist/runtime/local-authority.js +259 -14
  108. package/dist/runtime/local-authority.js.map +1 -1
  109. package/dist/runtime/policies.d.ts +89 -0
  110. package/dist/runtime/policies.js +152 -0
  111. package/dist/runtime/policies.js.map +1 -0
  112. package/dist/runtime/readiness.js +31 -1
  113. package/dist/runtime/readiness.js.map +1 -1
  114. package/dist/runtime/runtime.d.ts +21 -1
  115. package/dist/runtime/runtime.js +200 -7
  116. package/dist/runtime/runtime.js.map +1 -1
  117. package/dist/runtime/services-rules.d.ts +9 -0
  118. package/dist/runtime/services-rules.js +47 -1
  119. package/dist/runtime/services-rules.js.map +1 -1
  120. package/dist/runtime/services.d.ts +117 -9
  121. package/dist/runtime/services.js +154 -13
  122. package/dist/runtime/services.js.map +1 -1
  123. package/dist/server/admin.d.ts +21 -0
  124. package/dist/server/admin.js +114 -0
  125. package/dist/server/admin.js.map +1 -1
  126. package/dist/server/index.js +33 -6
  127. package/dist/server/index.js.map +1 -1
  128. package/dist/server/oauth.d.ts +32 -2
  129. package/dist/server/oauth.js +130 -23
  130. package/dist/server/oauth.js.map +1 -1
  131. package/dist/server/operators.d.ts +1 -0
  132. package/dist/server/operators.js +1 -1
  133. package/dist/server/operators.js.map +1 -1
  134. package/dist/server/project.d.ts +3 -0
  135. package/dist/server/project.js +2 -2
  136. package/dist/server/project.js.map +1 -1
  137. package/dist/testing/index.d.ts +11 -0
  138. package/dist/testing/index.js +7 -0
  139. package/dist/testing/index.js.map +1 -1
  140. package/docs/AGENT-OPERATIONS.md +1 -1
  141. package/docs/ARCHITECTURE.md +2 -1
  142. package/docs/CONNECTIONS.md +10 -3
  143. package/docs/EXTENSION-HOSTS.md +64 -5
  144. package/docs/GUARANTEES.md +82 -6
  145. package/docs/LOCAL-AUTHORITY.md +118 -0
  146. package/docs/POLICIES.md +121 -0
  147. package/docs/README.md +5 -2
  148. package/docs/SECURITY.md +69 -0
  149. package/docs/SIGN-IN-BROKER.md +77 -0
  150. package/docs/TRANSACTIONS.md +4 -0
  151. package/package.json +13 -9
  152. package/skills/.claude-plugin/marketplace.json +1 -1
  153. package/skills/.claude-plugin/plugin.json +1 -1
  154. package/skills/feltkit-agent/SKILL.md +1 -1
  155. package/skills/feltkit-build/SKILL.md +10 -0
  156. package/skills/feltkit-data/SKILL.md +13 -1
  157. package/skills/feltkit-services/SKILL.md +14 -1
@@ -39,15 +39,61 @@ export interface FilesReader {
39
39
  * your function first: holding the link is enough to download until it expires. Default
40
40
  * 5 minutes, at most 1 hour. Node server only.
41
41
  */
42
- link(id: string, options?: {
43
- expiresInSeconds?: number;
44
- disposition?: "attachment" | "inline";
45
- }): Promise<FileLink>;
42
+ link(id: string, options?: FileLinkOptions): Promise<FileLink>;
43
+ }
44
+ export interface FileLinkOptions {
45
+ /** Default 300 (3600 with `cache`); at most 3600. With `cache`, at least 2. */
46
+ expiresInSeconds?: number;
47
+ disposition?: "attachment" | "inline";
48
+ /**
49
+ * A cacheable link. The same caller asking for the same file (same content, variant and
50
+ * disposition) gets the same URL for half of `expiresInSeconds` (`stableUntil`), and the
51
+ * response is `Cache-Control: private, max-age=<seconds until expiresAt>, immutable` with an
52
+ * ETag, so a browser downloads it once. The tradeoff: a copy a browser already holds stays
53
+ * usable until `expiresAt` (at most `expiresInSeconds`, ≤ 1 h) even if the file is removed or
54
+ * the caller loses access; new downloads through the link stop at once. Default false
55
+ * (`private, no-store`, a new URL every call).
56
+ */
57
+ cache?: boolean;
58
+ /** A declared image variant (`services.files.variants`), served instead of the original. */
59
+ variant?: string;
46
60
  }
47
61
  /** A capability URL for one file transfer. `url` is relative to the application's origin. */
48
62
  export interface FileLink {
49
63
  url: string;
50
64
  expiresAt: string;
65
+ /** `cache: true`: until when the same request returns this same URL (then a new one, valid until its own `expiresAt`). */
66
+ stableUntil?: string;
67
+ /** `variant`: what the link serves. */
68
+ variant?: FileVariantInfo;
69
+ }
70
+ /**
71
+ * A variant as a link sees it.
72
+ * ready derived and stored: the link serves it (width, height, contentType)
73
+ * pending not derived yet: the first download derives it (or serves the original, saying why)
74
+ * original it cannot be derived from this file (reason): the link serves the original
75
+ * The download says what it served in `X-FeltKit-Variant` (the name, or `original`) and, for the
76
+ * original, `X-FeltKit-Variant-Reason`.
77
+ */
78
+ export interface FileVariantInfo {
79
+ name: string;
80
+ status: "ready" | "pending" | "original";
81
+ reason?: string;
82
+ width?: number;
83
+ height?: number;
84
+ contentType?: string;
85
+ }
86
+ /** One image variant: the largest box it fits in (`inside`, default) or fills and crops to (`cover`). Never larger than the original. */
87
+ export interface FileVariantSpec {
88
+ /** Pixels, 1-4096. */
89
+ width: number;
90
+ /** Pixels, 1-4096. Required with `fit: "cover"`. */
91
+ height?: number;
92
+ fit?: "inside" | "cover";
93
+ /** auto (default): PNG when the result has transparency, else JPEG. */
94
+ format?: "auto" | "jpeg" | "png";
95
+ /** JPEG quality, 1-100. Default 80. */
96
+ quality?: number;
51
97
  }
52
98
  export interface FilesWriter extends FilesReader {
53
99
  upload(input: UploadInput): Promise<FileInfo>;
@@ -96,11 +142,49 @@ export interface NotificationsReader {
96
142
  type?: string;
97
143
  }): Promise<NotificationInfo[]>;
98
144
  get(id: string): Promise<NotificationInfo>;
145
+ /**
146
+ * The caller's inbox, one bounded page at a time (FRAME-GAP-08): newest first (`createdAt`
147
+ * descending, then `id` ascending), read from the recipient's timeline index, never the whole
148
+ * history. `limit` 1-100 (default 50). Pass `nextCursor` back, with the same `unread`, `type`
149
+ * and `limit`, for the next page; a cursor from another recipient, filter or limit is refused
150
+ * (INVALID_ARGUMENT). With `unread`, a page may hold fewer than `limit` items, even none, and
151
+ * still have a `nextCursor`: only a page without one is the end.
152
+ */
153
+ page(options?: NotificationPageOptions): Promise<NotificationPage>;
154
+ /** How many of the caller's notifications are unread, up to `max` (1-500, default 100). `complete: false`: at least `count` ("99+"). */
155
+ unreadCount(options?: {
156
+ type?: string;
157
+ max?: number;
158
+ }): Promise<{
159
+ count: number;
160
+ complete: boolean;
161
+ }>;
162
+ }
163
+ export interface NotificationPageOptions {
164
+ unread?: boolean;
165
+ type?: string;
166
+ limit?: number;
167
+ cursor?: string;
168
+ }
169
+ export interface NotificationPage {
170
+ items: NotificationInfo[];
171
+ nextCursor?: string;
99
172
  }
100
173
  export interface NotificationsWriter extends NotificationsReader {
101
174
  send(input: SendNotificationInput): Promise<NotificationInfo>;
102
175
  markRead(id: string): Promise<NotificationInfo>;
103
176
  dismiss(id: string): Promise<NotificationInfo>;
177
+ /**
178
+ * Mark the caller's unread notifications read (of `type`, if given), at most 1,000 per call, each
179
+ * as `markRead` does (version-checked, audited). `complete: false`: more remain, call again. Not
180
+ * atomic across notifications.
181
+ */
182
+ markAllRead(options?: {
183
+ type?: string;
184
+ }): Promise<{
185
+ marked: number;
186
+ complete: boolean;
187
+ }>;
104
188
  }
105
189
  /** Variables for the current environment. Secrets (credential references) are not offered. */
106
190
  export interface ConfigurationReader {
@@ -137,8 +221,16 @@ export interface BoundServices {
137
221
  webhooks?: WebhooksWriter;
138
222
  }
139
223
  export interface ServicesConfig {
224
+ /**
225
+ * `variants`: image renditions a link may ask for (`files.link(id, { variant })`), by name, e.g.
226
+ * `{ w640: { width: 640 }, avatar64: { width: 64, height: 64, fit: "cover" } }`. Derived once per
227
+ * file and variant from JPEG and PNG originals, kept with the original's bytes and removed with
228
+ * them. `maxVariantPixels` (default 24,000,000): larger images are served as the original.
229
+ */
140
230
  files?: boolean | {
141
231
  maxBytes?: number;
232
+ variants?: Record<string, FileVariantSpec>;
233
+ maxVariantPixels?: number;
142
234
  };
143
235
  /** `types`: the notification types this application sends, offered in Studio. */
144
236
  notifications?: boolean | {
@@ -210,6 +302,26 @@ export interface ServiceStatus {
210
302
  page?: string;
211
303
  }
212
304
  export declare const CONFIGURATION_ENVIRONMENT: Record<string, "development" | "staging" | "production">;
305
+ /** What `GET /api/files/<token>` serves. */
306
+ export interface DownloadedFile {
307
+ file: FileInfo;
308
+ bytes: Uint8Array;
309
+ disposition: "attachment" | "inline";
310
+ /** Of the bytes served (a variant's own type). */
311
+ contentType?: string;
312
+ /** For Content-Disposition (a variant's name says which). */
313
+ filename: string;
314
+ /** A strong ETag: the SHA-256 of the bytes served. */
315
+ etag: string;
316
+ /** A cacheable link: seconds until it expires (the response's max-age). null: not cacheable (no-store). */
317
+ maxAgeSeconds: number | null;
318
+ /** A variant link: whether the variant was served, or the original and why. */
319
+ variant?: {
320
+ name: string;
321
+ served: "variant" | "original";
322
+ reason?: string;
323
+ };
324
+ }
213
325
  /** One pass of the services worker (FeltKitRuntime.runServices). */
214
326
  export interface ServiceTick {
215
327
  /** Job attempts made. */
@@ -432,11 +544,7 @@ export declare class ServicesHost {
432
544
  * `GET /api/files/<token>`: the file a download link names. The link is the authority (the
433
545
  * function that issued it authorized the reader); the file must still exist and verify.
434
546
  */
435
- redeemDownload(token: string): Promise<{
436
- file: FileInfo;
437
- bytes: Uint8Array;
438
- disposition: "attachment" | "inline";
439
- }>;
547
+ redeemDownload(token: string): Promise<DownloadedFile>;
440
548
  /**
441
549
  * `PUT /api/files/<token>`: create the file an upload link allows, as the principal who created
442
550
  * the link, with the link's metadata. The link is consumed first, so it works once.
@@ -30,17 +30,17 @@
30
30
  * File *bytes*: AppPort Files stores metadata and a `storageKey`; the bytes are in the
31
31
  * same instance (runtime/content.ts). Upload stores the bytes first (verified on every
32
32
  * read), then commits the metadata once, so a file record never points at bytes that
33
- * were not stored; deleting a file removes its bytes.
33
+ * were not stored; deleting a file removes its bytes and the image variants derived from them.
34
34
  */
35
35
  import { jobContextOperation } from "./job-context.js";
36
36
  import { createServices, isServiceAuthorityError, parseConfigurationExport, MAX_EVIDENCE_LOOKUP_LIMIT, VERSION, } from "@appport/services";
37
- import { randomUUID } from "node:crypto";
37
+ import { createHash, randomUUID } from "node:crypto";
38
38
  import { FeltKitError, isFeltKitError } from "../errors.js";
39
39
  import { grantsPermission } from "@appport/authorization";
40
- import { FileContent, FILE_CONTENT_COLLECTION } from "./content.js";
40
+ import { derivedLinkToken, FileContent, FILE_CONTENT_COLLECTION } from "./content.js";
41
41
  import { OUTBOX_COLLECTION, outboxStore, performOutbox, settled } from "./transactions.js";
42
42
  import { readAll } from "./data.js";
43
- import { servicesDependencyProblem } from "./services-rules.js";
43
+ import { DEFAULT_MAX_VARIANT_PIXELS, servicesDependencyProblem, VARIANT_CODEC } from "./services-rules.js";
44
44
  import { EnvironmentCredentials, credentialId, isConnectionId, isCustodyError, redactSecret } from "./credentials.js";
45
45
  import { systemPrincipal } from "./authority.js";
46
46
  export { FILE_CONTENT_COLLECTION };
@@ -130,6 +130,11 @@ export class ServicesHost {
130
130
  #tenantId;
131
131
  #applicationId;
132
132
  #maxBytes;
133
+ /** Declared image variants, with the digest of each spec (and the codec) that derived rows are keyed to. */
134
+ #variants;
135
+ #maxVariantPixels;
136
+ /** Variants being derived in this process, so concurrent first downloads derive once. */
137
+ #deriving = new Map();
133
138
  /** requestId → principal for invocations currently allowed to cause service effects */
134
139
  #bound = new Map();
135
140
  #lastError;
@@ -148,6 +153,11 @@ export class ServicesHost {
148
153
  this.credentials = options.credentials ?? new EnvironmentCredentials();
149
154
  const config = options.config;
150
155
  this.#maxBytes = typeof config.files === "object" ? config.files.maxBytes ?? DEFAULT_MAX_FILE_BYTES : DEFAULT_MAX_FILE_BYTES;
156
+ this.#maxVariantPixels = typeof config.files === "object" ? config.files.maxVariantPixels ?? DEFAULT_MAX_VARIANT_PIXELS : DEFAULT_MAX_VARIANT_PIXELS;
157
+ this.#variants = new Map(Object.entries(typeof config.files === "object" ? config.files.variants ?? {} : {}).map(([name, spec]) => {
158
+ const normal = { width: spec.width, height: spec.height ?? null, fit: spec.fit ?? "inside", format: spec.format ?? "auto", quality: spec.quality ?? 80 };
159
+ return [name, { spec, digest: createHash("sha256").update(JSON.stringify([VARIANT_CODEC, normal, this.#maxVariantPixels])).digest("hex") }];
160
+ }));
151
161
  this.apiKeyRoles = Object.freeze([...(typeof config.apiKeys === "object" ? config.apiKeys.roles ?? [] : [])]);
152
162
  this.jobHandlers = Object.freeze({ ...(typeof config.jobs === "object" ? config.jobs.handlers ?? {} : {}) });
153
163
  this.notificationTypes = Object.freeze([...(typeof config.notifications === "object" ? config.notifications.types ?? [] : [])]);
@@ -539,8 +549,85 @@ export class ServicesHost {
539
549
  if (!record)
540
550
  throw new FeltKitError("NOT_FOUND", "This file no longer exists.");
541
551
  const file = toInfo(record);
542
- const { bytes } = await this.#content.read(file.id, String(record.storageKey), file.checksum);
543
- return { file, bytes, disposition: grant.disposition };
552
+ // A link serves the content it was issued for, never other content behind the same id.
553
+ if (grant.checksum && file.checksum !== grant.checksum)
554
+ throw new FeltKitError("NOT_FOUND", "This file's content changed after the link was issued; ask for a new link.");
555
+ const storageKey = String(record.storageKey);
556
+ const maxAgeSeconds = grant.cache ? Math.max(0, Math.floor((grant.expiresAt - Date.now()) / 1000)) : null;
557
+ const served = (bytes, contentType, name, variant) => ({
558
+ file,
559
+ bytes,
560
+ disposition: grant.disposition,
561
+ ...(contentType ? { contentType } : {}),
562
+ filename: name,
563
+ etag: `"${createHash("sha256").update(bytes).digest("hex")}"`,
564
+ maxAgeSeconds,
565
+ ...(variant ? { variant } : {}),
566
+ });
567
+ const original = async (variant) => served((await this.#content.read(file.id, storageKey, file.checksum)).bytes, file.contentType, file.name, variant);
568
+ if (!grant.variant)
569
+ return original();
570
+ const declared = this.#variants.get(grant.variant);
571
+ if (!declared)
572
+ return original({ name: grant.variant, served: "original", reason: `The variant "${grant.variant}" is no longer declared (services.files.variants); the original is served.` });
573
+ const row = await this.#derivedVariant(file, storageKey, grant.variant, declared);
574
+ if (row.status !== "derived")
575
+ return original({ name: grant.variant, served: "original", reason: row.reason ?? "The variant could not be derived; the original is served." });
576
+ const extension = row.contentType === "image/png" ? ".png" : ".jpg";
577
+ return served(this.#content.readVariant(row), row.contentType, `${file.name.replace(/\.[^./]*$/, "")}-${grant.variant}${extension}`, { name: grant.variant, served: "variant" });
578
+ }
579
+ /** The declared variant `name`, or INVALID_ARGUMENT naming the declared ones. */
580
+ #variant(name) {
581
+ const declared = typeof name === "string" ? this.#variants.get(name) : undefined;
582
+ if (!declared) {
583
+ const names = [...this.#variants.keys()];
584
+ throw new FeltKitError("INVALID_ARGUMENT", `No file variant ${JSON.stringify(name)}. ${names.length ? `Declared: ${names.join(", ")}.` : "Declare variants in feltkit({ services: { files: { variants } } })."}`);
585
+ }
586
+ return { name: name, ...declared };
587
+ }
588
+ /** What a link to `name` of these bytes will serve, from what is stored (nothing is derived here). */
589
+ async #variantInfo(storageKey, name, digest) {
590
+ const row = await this.#content.variant(storageKey, name);
591
+ if (!row || row.spec !== digest)
592
+ return { name, status: "pending" };
593
+ if (row.status !== "derived")
594
+ return { name, status: "original", ...(row.reason ? { reason: row.reason } : {}) };
595
+ return { name, status: "ready", ...(row.width ? { width: row.width } : {}), ...(row.height ? { height: row.height } : {}), ...(row.contentType ? { contentType: row.contentType } : {}) };
596
+ }
597
+ /**
598
+ * The stored variant of a file's bytes, derived (once) when it is missing or was derived under
599
+ * another spec. An image it cannot be derived from is stored as `original` with the reason, so the
600
+ * work is not repeated on every download.
601
+ */
602
+ async #derivedVariant(file, storageKey, name, declared) {
603
+ const stored = await this.#content.variant(storageKey, name);
604
+ if (stored && stored.spec === declared.digest)
605
+ return stored;
606
+ const key = `${storageKey}\0${name}\0${declared.digest}`;
607
+ const running = this.#deriving.get(key);
608
+ if (running)
609
+ return running;
610
+ const work = (async () => {
611
+ const { bytes } = await this.#content.read(file.id, storageKey, file.checksum);
612
+ const { deriveVariant } = await import("./image-variants.js");
613
+ const derived = deriveVariant(bytes, declared.spec, { maxPixels: this.#maxVariantPixels });
614
+ const row = await this.#content.storeVariant(derived.status === "derived"
615
+ ? { source: storageKey, variant: name, spec: declared.digest, status: "derived", bytes: derived.bytes, width: derived.width, height: derived.height, contentType: derived.contentType }
616
+ : { source: storageKey, variant: name, spec: declared.digest, status: "original", reason: derived.reason });
617
+ // The bytes were released while this was derived (the file was removed): do not leave the variant behind.
618
+ if (!(await this.#content.has(storageKey))) {
619
+ await this.#content.releaseVariants(storageKey);
620
+ throw new FeltKitError("NOT_FOUND", "This file no longer exists.");
621
+ }
622
+ return row;
623
+ })();
624
+ this.#deriving.set(key, work);
625
+ try {
626
+ return await work;
627
+ }
628
+ finally {
629
+ this.#deriving.delete(key);
630
+ }
544
631
  }
545
632
  /**
546
633
  * `PUT /api/files/<token>`: create the file an upload link allows, as the principal who created
@@ -674,8 +761,13 @@ export class ServicesHost {
674
761
  }
675
762
  // 2. Remove them, keeping what was removed.
676
763
  const taken = await this.#content.take(storageKey);
764
+ // Variants derived from the bytes go with them (also when an earlier attempt removed the bytes).
765
+ const variants = async () => {
766
+ const removed = await this.#content.releaseVariants(storageKey);
767
+ return removed ? { variantsReleased: removed } : {};
768
+ };
677
769
  if (!taken.removed)
678
- return { released: false };
770
+ return { released: false, ...(await variants()) };
679
771
  // 3. Look again: a file may have been made to name these bytes (Services' management API takes any
680
772
  // storageKey) between the lookup and the removal. Then, or if this cannot be established, put
681
773
  // them back: nothing is left released on an unknown.
@@ -691,7 +783,7 @@ export class ServicesHost {
691
783
  await taken.restore();
692
784
  return { released: false, retained: true, referencedBy: after, raced: true };
693
785
  }
694
- return { released: true };
786
+ return { released: true, ...(await variants()) };
695
787
  }
696
788
  finally {
697
789
  release();
@@ -821,11 +913,37 @@ export class ServicesHost {
821
913
  return { file, bytes, text: () => new TextDecoder().decode(bytes) };
822
914
  },
823
915
  link: async (id, options = {}) => {
824
- await reader.get(id); // the caller must be able to read it (files.read), and it must exist
825
- const ttl = linkSeconds(options.expiresInSeconds, 300);
826
- const expiresAt = Date.now() + ttl * 1000;
827
- const token = await this.#content.issueLink({ kind: "download", fileId: id, expiresAt, disposition: options.disposition === "inline" ? "inline" : "attachment" });
828
- return { url: `/api/files/${token}`, expiresAt: new Date(expiresAt).toISOString() };
916
+ // The caller must be able to read it (files.read, its workspace), and it must exist.
917
+ use();
918
+ this.#requireFiles();
919
+ reads.add("files");
920
+ const record = await owned(id);
921
+ const file = toInfo(record);
922
+ const storageKey = String(record.storageKey);
923
+ const disposition = options.disposition === "inline" ? "inline" : "attachment";
924
+ const variant = options.variant === undefined ? null : this.#variant(options.variant);
925
+ const variantInfo = variant ? { variant: await this.#variantInfo(storageKey, variant.name, variant.digest) } : {};
926
+ const grant = { kind: "download", fileId: id, disposition, ...(file.checksum ? { checksum: file.checksum } : {}), ...(variant ? { variant: variant.name } : {}) };
927
+ if (!options.cache) {
928
+ const ttl = linkSeconds(options.expiresInSeconds, 300);
929
+ const expiresAt = Date.now() + ttl * 1000;
930
+ const token = await this.#content.issueLink({ ...grant, expiresAt });
931
+ return { url: `/api/files/${token}`, expiresAt: new Date(expiresAt).toISOString(), ...variantInfo };
932
+ }
933
+ // Cacheable: time is cut into windows of half the lifetime. Within one window the same scope
934
+ // derives the same token; each URL lives until the end of the window after its own, so it is
935
+ // always issued with at least half its lifetime left, and never lives longer than asked.
936
+ const lifetime = linkSeconds(options.expiresInSeconds, 3600);
937
+ if (lifetime < 2)
938
+ throw new FeltKitError("INVALID_ARGUMENT", "A cacheable link needs expiresInSeconds of at least 2.");
939
+ const windowMs = Math.floor(lifetime / 2) * 1000;
940
+ const window = Math.floor(Date.now() / windowMs);
941
+ const expiresAt = (window + 2) * windowMs;
942
+ // The scope: this file's content (and variant spec) as it is now, and this caller in this
943
+ // workspace. Another principal never receives this URL; changed content gets a new one.
944
+ const token = derivedLinkToken([this.#applicationId, id, storageKey, file.checksum ?? null, variant?.name ?? null, variant?.digest ?? null, disposition, principal.type, principal.id, callerTenant, windowMs, window]);
945
+ await this.#content.issueDerivedLink(token, { ...grant, expiresAt, cache: true });
946
+ return { url: `/api/files/${token}`, expiresAt: new Date(expiresAt).toISOString(), stableUntil: new Date((window + 1) * windowMs).toISOString(), ...variantInfo };
829
947
  },
830
948
  };
831
949
  if (!writable)
@@ -959,6 +1077,18 @@ export class ServicesHost {
959
1077
  return page.items.map(toNotification);
960
1078
  },
961
1079
  get: async (id) => toNotification(await this.#record(service().get(this.#tenantId, id, me()))),
1080
+ page: async (options = {}) => {
1081
+ const s = paging(service());
1082
+ const verified = me();
1083
+ const page = await this.#record(s.inbox(this.#tenantId, { recipient: verified.principalId, ...(options.unread ? { unread: true } : {}), ...(options.type ? { type: options.type } : {}), ...(options.limit !== undefined ? { limit: options.limit } : {}), ...(options.cursor ? { cursor: options.cursor } : {}) }, verified));
1084
+ return { items: page.items.map(toNotification), ...(page.nextCursor ? { nextCursor: page.nextCursor } : {}) };
1085
+ },
1086
+ unreadCount: async (options = {}) => {
1087
+ const s = paging(service());
1088
+ const verified = me();
1089
+ const result = await this.#record(s.unreadCount(this.#tenantId, { recipient: verified.principalId, ...(options.type ? { type: options.type } : {}), ...(options.max !== undefined ? { max: options.max } : {}) }, verified));
1090
+ return { count: result.count, complete: result.complete };
1091
+ },
962
1092
  };
963
1093
  if (!writable)
964
1094
  return reader;
@@ -982,6 +1112,10 @@ export class ServicesHost {
982
1112
  },
983
1113
  markRead: async (id) => toNotification(await this.#record(service().markRead(this.#tenantId, id, me()))),
984
1114
  dismiss: async (id) => toNotification(await this.#record(service().dismiss(this.#tenantId, id, me()))),
1115
+ markAllRead: async (options = {}) => {
1116
+ const result = await this.#record(paging(service()).markAllRead(this.#tenantId, { ...(options.type ? { type: options.type } : {}) }, me()));
1117
+ return { marked: result.marked, complete: result.complete };
1118
+ },
985
1119
  };
986
1120
  }
987
1121
  #bindConfiguration(principal, requestId, reads, writable, used) {
@@ -1234,6 +1368,13 @@ const UNCONFIGURED = {
1234
1368
  jobs: "Enabled; no job handlers declared (services.jobs.handlers).",
1235
1369
  schedules: "Enabled; no active schedules.",
1236
1370
  };
1371
+ function paging(service) {
1372
+ const s = service;
1373
+ if (typeof s.inbox !== "function" || typeof s.unreadCount !== "function" || typeof s.markAllRead !== "function") {
1374
+ throw new FeltKitError("FAILED_PRECONDITION", `Notification paging (page, unreadCount, markAllRead) needs @appport/services with NotificationService.inbox, unreadCount and markAllRead (after 0.19.0); this installation has ${VERSION}.`, { hint: "Update @appport/services. list() works on every release." });
1375
+ }
1376
+ return s;
1377
+ }
1237
1378
  function toNotification(item) {
1238
1379
  return {
1239
1380
  id: item.id,