@crud-api/core 0.3.0 → 0.4.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.
@@ -1,5 +1,5 @@
1
1
  import type { Codec } from "@ecson/core";
2
- import type { OperationName, Resource, ResourceId } from "./types.ts";
2
+ import type { OperationName, Projection, Resource, ResourceId } from "./types.ts";
3
3
  import { CodeRegistry, type Warning } from "./warnings.ts";
4
4
  /**
5
5
  * The context of an extension hook: Warnings go to the sink of the operation (WARN_EXTENSION_CODES); the clock and the
@@ -23,6 +23,14 @@ export interface HookCtx {
23
23
  * declared `nativeTypes` in their plain JSON form (D128). Pure; the Resource given is not changed.
24
24
  */
25
25
  stored(resource: Resource): Resource;
26
+ /**
27
+ * The Resources of a Collection of the data provider with the given Resource IDs, in the order asked: `null` for each
28
+ * one that does not exist or whose ID the Collection's key rejects, and `null` for the whole call when the Collection
29
+ * does not exist, is not a Slug or is claimed by an extension (D129). It reads with the operation's I/O (the
30
+ * transaction, inside a write scope), and each distinct Resource is authorized as a `get` of the Client: a refusal
31
+ * fails the operation with ACCESS_DENIED.
32
+ */
33
+ read(collection: string, ids: readonly ResourceId[]): Promise<(Resource | null)[] | null>;
26
34
  }
27
35
  /**
28
36
  * A Parameter an extension adds (design 7, "extra Parameters"; D116): recognized by the listed operations, so that it
@@ -50,6 +58,12 @@ export interface Extension {
50
58
  readonly versions: readonly string[];
51
59
  /** Names of the extensions this one needs (Schema needs Metadata, `schema/spec.yaml`). */
52
60
  readonly requires?: readonly string[];
61
+ /**
62
+ * Names of extensions that, when enabled too, must come after this one in `extensions`, so their hooks see what this
63
+ * one's hooks change (Relationships before Metadata, whose hash covers the stored Resource); construction fails
64
+ * otherwise (D137).
65
+ */
66
+ readonly before?: readonly string[];
53
67
  /** Needs the system storage of design 6.10 (Schema, Views, Async). */
54
68
  readonly needsSystemStorage?: boolean;
55
69
  /** Reserved Fields this extension defines and handles (FIELDS_EXTENSION_RESERVED), such as `_meta`. */
@@ -77,11 +91,24 @@ export interface Extension {
77
91
  * PARAM_EXPECT_MATCH. Throwing a CrudError fails the operation without writing (Metadata META_DOC_CONDITIONAL).
78
92
  */
79
93
  precondition?(input: PreconditionInput, ctx: HookCtx): void | Promise<void>;
80
- /** Called on the Resources read by `get` and `list`, after the provider's projection push-down and before the core's own projection (D74). */
81
- afterRead?(input: {
82
- readonly collection: string;
83
- readonly resources: Resource[];
84
- }, ctx: HookCtx): Resource[] | Promise<Resource[]>;
94
+ /**
95
+ * Called on the Resources read by `get` and `list`, after the provider's projection push-down and before the core's
96
+ * own projection (D74), with the operation and the extension's Parameters (D129).
97
+ */
98
+ afterRead?(input: AfterReadInput, ctx: HookCtx): Resource[] | Promise<Resource[]>;
99
+ }
100
+ /** What `afterRead` receives (D129). */
101
+ export interface AfterReadInput {
102
+ readonly operation: OperationName;
103
+ readonly collection: string;
104
+ readonly resources: Resource[];
105
+ /** The extension's own Parameters the request sent. */
106
+ readonly params: ExtensionParams;
107
+ /**
108
+ * The Client's Projection, normalized, or null when none was sent. The core applies it after the hooks (design 6.5);
109
+ * hooks read it to leave alone what it drops, whether or not the provider pushed it down (D129).
110
+ */
111
+ readonly projection: Projection | null;
85
112
  }
86
113
  /** What `beforeWrite` receives (D116). */
87
114
  export interface BeforeWriteInput {
@@ -143,6 +170,9 @@ export declare class ExtensionRegistry {
143
170
  precondition(input: Omit<PreconditionInput, "params"> & {
144
171
  readonly params?: Readonly<Record<string, unknown>>;
145
172
  }, ctx: HookCtx): Promise<void>;
146
- /** Runs every `afterRead` hook in the order of the extensions. */
147
- afterRead(collection: string, resources: Resource[], ctx: HookCtx): Promise<Resource[]>;
173
+ /** Runs every `afterRead` hook in the order of the extensions; each hook gets its own Parameters (D129). */
174
+ afterRead(input: Omit<AfterReadInput, "params" | "projection"> & {
175
+ readonly params?: Readonly<Record<string, unknown>>;
176
+ readonly projection?: Projection | null;
177
+ }, ctx: HookCtx): Promise<Resource[]>;
148
178
  }
@@ -44,6 +44,11 @@ export class ExtensionRegistry {
44
44
  throw new Error(`extensions ${owner} and ${extension.name} both define the Parameter ${parameter.name}`);
45
45
  parameters.set(parameter.name, extension.name);
46
46
  }
47
+ for (const later of extension.before ?? []) {
48
+ const at = extensions.findIndex((e) => e.name === later);
49
+ if (at !== -1 && at < extensions.indexOf(extension))
50
+ throw new Error(`extension ${extension.name} must come before extension ${later}`);
51
+ }
47
52
  for (const required of extension.requires ?? []) {
48
53
  if (!names.has(required))
49
54
  throw new Error(`extension ${extension.name} requires extension ${required}, which is not enabled`);
@@ -88,12 +93,13 @@ export class ExtensionRegistry {
88
93
  await extension.precondition({ ...rest, params: paramsOf(extension, params) }, ctx);
89
94
  }
90
95
  }
91
- /** Runs every `afterRead` hook in the order of the extensions. */
92
- async afterRead(collection, resources, ctx) {
93
- let current = resources;
96
+ /** Runs every `afterRead` hook in the order of the extensions; each hook gets its own Parameters (D129). */
97
+ async afterRead(input, ctx) {
98
+ const { params = {}, projection = null, ...rest } = input;
99
+ let current = input.resources;
94
100
  for (const extension of this.list) {
95
101
  if (extension.afterRead !== undefined)
96
- current = await extension.afterRead({ collection, resources: current }, ctx);
102
+ current = await extension.afterRead({ ...rest, resources: current, params: paramsOf(extension, params), projection }, ctx);
97
103
  }
98
104
  return current;
99
105
  }
package/dist/index.d.ts CHANGED
@@ -27,7 +27,7 @@ export { createCrudServer, BASE_SPEC } from "./server.ts";
27
27
  export type { CrudServer, CrudServerOptions, ProtocolRegistration, ServerDescription } from "./server.ts";
28
28
  export type { OperationRequest, OperationResult, ResultMeta } from "./operation.ts";
29
29
  export { ExtensionRegistry, KNOWN_RESERVED_FIELDS } from "./extensions.ts";
30
- export type { BeforeWriteInput, Extension, ExtensionParameter, ExtensionParams, HookCtx, PreconditionInput } from "./extensions.ts";
30
+ export type { AfterReadInput, BeforeWriteInput, Extension, ExtensionParameter, ExtensionParams, HookCtx, PreconditionInput } from "./extensions.ts";
31
31
  export { atomicity, decideWriteMode } from "./write-policy.ts";
32
32
  export type { Atomicity, WriteMode, WritePolicyInput } from "./write-policy.ts";
33
33
  export { assertClientId, assertNoStrayId, assertResource, assertSubjectId, canonicalId, checkFieldNames, dropReservedChanges, dropReservedFields, keyIsTopLevel } from "./subject.ts";
@@ -85,6 +85,18 @@ export interface OpContext {
85
85
  query: ParsedQuery | null;
86
86
  readonly counters: Counters;
87
87
  io: Io;
88
+ /** What the hook context keeps for the whole operation (D129, D137). */
89
+ hooks?: HookState;
90
+ }
91
+ /** The state the hook contexts of one operation share (D137). */
92
+ interface HookState {
93
+ /** `collection` and Resource ID, as asked, of the Resources `HookCtx.read` already authorized. */
94
+ readonly authorized: Set<string>;
95
+ /** `collection` and canonical ID of the Resources `HookCtx.read` already read (null: none). */
96
+ readonly reads: Map<string, Resource | null>;
97
+ /** The keys of the Warnings in the sink, for `warnOnce`, and how many of them were keyed. */
98
+ readonly warned: Set<string>;
99
+ keyed: number;
88
100
  }
89
101
  export declare const warnOf: (ctx: OpContext) => (warning: Warning) => void;
90
102
  /** The context of extension hooks (D116). */
@@ -173,3 +185,4 @@ export declare function undoImplicitCollection(ctx: OpContext): Promise<void>;
173
185
  export type PatchInput = NonNullable<OperationRequest["patch"]>;
174
186
  /** Applies a patch in memory to a copy of the Resource; failures are INVALID_PATCH. */
175
187
  export declare function applyPatch(resource: Resource, patch: PatchInput): Resource;
188
+ export {};
@@ -1,29 +1,90 @@
1
1
  import { assertWritableDepth } from "../depth.js";
2
2
  import { downgrade } from "../downgrade.js";
3
3
  import { CrudError } from "../errors.js";
4
- import { idOf } from "../ids.js";
4
+ import { assertValidId, idOf, isSlug } from "../ids.js";
5
5
  import { applyJsonPatch, applyMergePatch } from "../patch.js";
6
6
  import { sortKeys } from "../sorting.js";
7
7
  import { canonicalId } from "../subject.js";
8
8
  import { strictPolicy } from "../warnings.js";
9
+ const hookState = (ctx) => (ctx.hooks ??= { authorized: new Set(), reads: new Map(), warned: new Set(), keyed: 0 });
10
+ /** A Warning's code and members without its message, the identity `warnOnce` compares (D116). */
11
+ function warningKey(warning) {
12
+ const { message: _, ...members } = warning;
13
+ return JSON.stringify(Object.entries(members).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
14
+ }
9
15
  export const warnOf = (ctx) => (warning) => ctx.sink.warn(warning);
10
16
  /** The context of extension hooks (D116). */
11
17
  export const hookCtx = (ctx) => ({
12
18
  warn: warnOf(ctx),
13
19
  warnOnce: (warning) => {
14
- const { message: _, ...members } = warning;
15
- const same = (w) => {
16
- const { message: __, ...other } = w;
17
- return JSON.stringify(Object.entries(other).sort()) === JSON.stringify(Object.entries(members).sort());
18
- };
19
- if (!ctx.sink.list.some(same))
20
- ctx.sink.warn(warning);
20
+ // The sink's Warnings are keyed once each, so a hook that reports thousands of Warnings stays linear (D137).
21
+ const state = hookState(ctx);
22
+ const list = ctx.sink.list;
23
+ for (; state.keyed < list.length; state.keyed++)
24
+ state.warned.add(warningKey(list[state.keyed]));
25
+ if (state.warned.has(warningKey(warning)))
26
+ return;
27
+ ctx.sink.warn(warning);
21
28
  },
22
29
  clock: ctx.server.clock,
23
30
  principal: ctx.request.meta?.principal,
24
31
  codec: ctx.server.codec,
25
32
  stored: (resource) => downgrade(resource, ctx.caps.nativeTypes, ctx.server.codec).resource, // D128
33
+ read: (collection, ids) => hookRead(ctx, collection, ids),
26
34
  });
35
+ /**
36
+ * `HookCtx.read` (D129, D137): the Resources of another Collection by ID, with the operation's I/O. Each distinct ID
37
+ * is first authorized as a `get` with the request's metadata, before anything about the Collection or the ID is looked
38
+ * at, as a `get` would (so a refusal never depends on whether they exist). Resources already read in the operation are
39
+ * not read again.
40
+ */
41
+ async function hookRead(ctx, collection, ids) {
42
+ const server = ctx.server;
43
+ if (typeof collection !== "string")
44
+ return null;
45
+ const state = hookState(ctx);
46
+ if (server.authorize !== undefined) {
47
+ for (const id of new Set(ids)) {
48
+ const entry = JSON.stringify([collection, id]);
49
+ if (state.authorized.has(entry))
50
+ continue;
51
+ if (!(await server.authorize({ operation: "get", collection, id, ...(ctx.request.meta !== undefined ? { meta: ctx.request.meta } : {}) }))) {
52
+ throw new CrudError("ACCESS_DENIED", `the Client is not allowed to read the Resource ${String(id)} of ${collection}`);
53
+ }
54
+ state.authorized.add(entry);
55
+ }
56
+ }
57
+ if (!isSlug(collection) || server.extensions.claimant(collection) !== undefined)
58
+ return null;
59
+ const info = await server.provider.collection(collection, {});
60
+ if (info === null)
61
+ return null;
62
+ const options = withCodec(ctx);
63
+ const canonical = ids.map((id) => {
64
+ try {
65
+ assertValidId(id, info.key, options);
66
+ return canonicalId(id, info.key, options);
67
+ }
68
+ catch (error) {
69
+ if (error instanceof CrudError)
70
+ return undefined; // the key rejects it: no such Resource
71
+ throw error;
72
+ }
73
+ });
74
+ const entry = (id) => JSON.stringify([collection, id]);
75
+ const wanted = [...new Set(canonical.filter((id) => id !== undefined && !state.reads.has(entry(id))))];
76
+ if (wanted.length > 0) {
77
+ const result = expectKind(await read(ctx, { kind: "findByIds", collection, key: info.key, ids: wanted, projection: null }), "findByIds");
78
+ for (const id of wanted)
79
+ state.reads.set(entry(id), null);
80
+ for (const resource of result.resources) {
81
+ const id = idOf(resource, info.key, options);
82
+ if (id !== undefined)
83
+ state.reads.set(entry(canonicalId(id, info.key, options)), resource);
84
+ }
85
+ }
86
+ return canonical.map((id) => (id === undefined ? null : (state.reads.get(entry(id)) ?? null)));
87
+ }
27
88
  /** Runs the `precondition` hooks on the current state of a Resource the write targets (D116). */
28
89
  export async function precondition(ctx, current) {
29
90
  await ctx.server.extensions.precondition({ operation: ctx.operation, collection: ctx.info.slug, current, params: ctx.params.extension }, hookCtx(ctx));
@@ -24,7 +24,7 @@ function pushdown(ctx) {
24
24
  return { include: null, exclude: projection.exclude.filter((path) => !isHandled(path)) };
25
25
  }
26
26
  async function finish(ctx, resources) {
27
- const read = await ctx.server.extensions.afterRead(ctx.info.slug, resources, hookCtx(ctx));
27
+ const read = await ctx.server.extensions.afterRead({ operation: ctx.operation, collection: ctx.info.slug, resources, params: ctx.params.extension, projection: ctx.params.projection }, hookCtx(ctx));
28
28
  if (ctx.operation === "get")
29
29
  keepReserved(ctx, read[0]); // META_PROTOCOL_MIRROR (D116)
30
30
  const projection = ctx.params.projection;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crud-api/core",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "CRUD API reference implementation: data model, engine, provider contract, field lists, projection, sorting, pagination, patch engines, negotiation",
5
5
  "keywords": [
6
6
  "crud",