@easy-cms/core 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.d.ts +193 -10
  2. package/dist/index.js +748 -79
  3. package/package.json +1 -1
package/dist/index.d.ts CHANGED
@@ -263,9 +263,32 @@ interface ArrayField extends BaseField<'array', never> {
263
263
  interface GroupField extends BaseField<'group', never> {
264
264
  readonly fields: readonly Field[];
265
265
  }
266
- type Field = TextField | TextareaField | NumberField | BooleanField | DateField | EmailField | JsonField | SelectField | SlugField | RichTextField | UploadField | RelationshipField | ArrayField | GroupField;
266
+ /** One kind of block in a `blocks` field. */
267
+ interface Block {
268
+ /** Stored in each row as `blockType`. */
269
+ readonly slug: string;
270
+ readonly labels?: {
271
+ readonly singular?: Label;
272
+ readonly plural?: Label;
273
+ };
274
+ readonly fields: readonly Field[];
275
+ }
276
+ /**
277
+ * A list of rows, each one of several block kinds (e.g. hero, text, gallery), for pages that
278
+ * editors lay out themselves. Rows are `{ id, blockType, ...fields }`, stored as JSON.
279
+ */
280
+ interface BlocksField extends BaseField<'blocks', never> {
281
+ readonly blocks: readonly Block[];
282
+ readonly minRows?: number;
283
+ readonly maxRows?: number;
284
+ }
285
+ /** Fields whose value is a list of rows: `array` and `blocks`. */
286
+ declare const hasRows: (field: Field) => field is ArrayField | BlocksField;
287
+ /** The fields of one row of an `array` or `blocks` field (`undefined` for an unknown block). */
288
+ declare function rowFields(field: ArrayField | BlocksField, row: unknown): readonly Field[] | undefined;
289
+ type Field = TextField | TextareaField | NumberField | BooleanField | DateField | EmailField | JsonField | SelectField | SlugField | RichTextField | UploadField | RelationshipField | ArrayField | GroupField | BlocksField;
267
290
  type FieldType = Field['type'];
268
- declare const FIELD_TYPES: readonly ["text", "textarea", "number", "boolean", "date", "email", "json", "select", "slug", "richText", "upload", "relationship", "array", "group"];
291
+ declare const FIELD_TYPES: readonly ["text", "textarea", "number", "boolean", "date", "email", "json", "select", "slug", "richText", "upload", "relationship", "array", "group", "blocks"];
269
292
 
270
293
  interface StoredFile {
271
294
  readonly body: Uint8Array;
@@ -296,6 +319,39 @@ interface LocalStorageOptions {
296
319
  /** Stores files on the local disk. Suitable for servers with a persistent filesystem. */
297
320
  declare function localStorage(options?: LocalStorageOptions): StorageAdapter;
298
321
 
322
+ declare const WEBHOOK_EVENTS: readonly ["create", "update", "delete", "publish", "unpublish", "draft"];
323
+ /**
324
+ * `create`, `update`, `delete`: the stored document changed. `publish` / `unpublish`: its status
325
+ * changed (sent with `create` or `update`). `draft`: only a draft was saved; what is live did not
326
+ * change (collections with versions and drafts).
327
+ */
328
+ type WebhookEvent = (typeof WEBHOOK_EVENTS)[number];
329
+ interface WebhookConfig {
330
+ /** Where to POST events. */
331
+ readonly url: string;
332
+ /** Events to send. Default: all. */
333
+ readonly events?: readonly WebhookEvent[];
334
+ /** Collections to send events for. Default: all; `[]` for none. */
335
+ readonly collections?: readonly string[];
336
+ /** Globals to send events for. Default: all; `[]` for none. */
337
+ readonly globals?: readonly string[];
338
+ /** Signs each body: `x-easy-cms-signature: sha256=<hex HMAC-SHA256 of the body>`. */
339
+ readonly secret?: string;
340
+ /** Extra request headers, e.g. a token the receiver checks. */
341
+ readonly headers?: Readonly<Record<string, string>>;
342
+ }
343
+ /** What a webhook receives as JSON. */
344
+ interface WebhookPayload {
345
+ readonly event: WebhookEvent;
346
+ readonly collection?: string;
347
+ readonly global?: string;
348
+ readonly id?: ID;
349
+ /** The stored document (every locale, no hidden fields); for `delete`, as it was. */
350
+ readonly doc: Record<string, unknown>;
351
+ /** ISO time of the change. */
352
+ readonly timestamp: string;
353
+ }
354
+
299
355
  type Data$2 = Record<string, unknown>;
300
356
  type MaybePromise<T> = T | Promise<T>;
301
357
  type Operation = 'create' | 'update';
@@ -384,6 +440,8 @@ interface CollectionConfig {
384
440
  * it is published again.
385
441
  */
386
442
  readonly versions?: boolean | VersionsConfig;
443
+ /** Allow scheduling publish/unpublish for a later time (needs `drafts`). */
444
+ readonly schedule?: boolean;
387
445
  /** Live preview: the page that shows a document, e.g. `({ doc }) => \`/posts/${doc.slug}\``. */
388
446
  readonly preview?: PreviewURL;
389
447
  readonly access?: CollectionAccess;
@@ -396,6 +454,8 @@ interface GlobalConfig {
396
454
  readonly drafts?: boolean;
397
455
  /** Keep a snapshot of every save. See `CollectionConfig.versions`. */
398
456
  readonly versions?: boolean | VersionsConfig;
457
+ /** Allow scheduling publish/unpublish for a later time (needs `drafts`). */
458
+ readonly schedule?: boolean;
399
459
  /** Live preview: the page that shows the global. See `CollectionConfig.preview`. */
400
460
  readonly preview?: PreviewURL;
401
461
  readonly access?: GlobalAccess;
@@ -464,6 +524,14 @@ interface Config {
464
524
  * `auth.trustedOrigins` are always allowed, with cookies. Default: none.
465
525
  */
466
526
  readonly cors?: readonly string[] | '*';
527
+ /**
528
+ * Lets a cron service run due scheduled jobs: `GET <api>/jobs/run` with
529
+ * `Authorization: Bearer <cronSecret>`. Default: the `CRON_SECRET` environment variable (the
530
+ * convention of Vercel Cron). Logged-in admins can always run jobs.
531
+ */
532
+ readonly cronSecret?: string;
533
+ /** Endpoints notified when content changes, e.g. to rebuild a static site. */
534
+ readonly webhooks?: readonly WebhookConfig[];
467
535
  /** Content in several languages: fields with `localized: true` hold one value per locale. */
468
536
  readonly localization?: LocalizationConfig | null;
469
537
  readonly routes?: RoutesConfig;
@@ -596,16 +664,38 @@ type FieldValue<F extends Field, C extends Config = Config> = F extends {
596
664
  }>[] : F extends {
597
665
  readonly type: 'group';
598
666
  readonly fields: infer Sub extends readonly Field[];
599
- } ? FieldsValue<Sub, C> : never;
667
+ } ? FieldsValue<Sub, C> : F extends {
668
+ readonly type: 'blocks';
669
+ readonly blocks: infer B extends readonly Block[];
670
+ } ? BlockValue<B[number], C>[] : never;
671
+ /** One row of a `blocks` field: the block's fields plus `id` and `blockType` (distributes over kinds). */
672
+ type BlockValue<B, C extends Config> = B extends {
673
+ readonly slug: infer S;
674
+ readonly fields: infer Sub extends readonly Field[];
675
+ } ? Simplify<FieldsValue<Sub, C> & {
676
+ id: string;
677
+ blockType: S;
678
+ }> : never;
679
+ type BlockInput<B> = B extends {
680
+ readonly slug: infer S;
681
+ readonly fields: infer Sub extends readonly Field[];
682
+ } ? Simplify<FieldsInput<Sub> & {
683
+ id?: string;
684
+ blockType: S;
685
+ }> : never;
600
686
  type Visible<Fs extends readonly Field[]> = Exclude<Fs[number], {
601
687
  readonly hidden: true;
602
688
  }>;
603
- type RequiredFields<Fs extends readonly Field[]> = Extract<Visible<Fs>, {
689
+ /** Always set when read: required fields, and lists and groups (empty `[]` / `{}` otherwise). */
690
+ type Present = {
604
691
  readonly required: true;
605
- }>;
606
- type OptionalFields<Fs extends readonly Field[]> = Exclude<Visible<Fs>, {
607
- readonly required: true;
608
- }>;
692
+ } | {
693
+ readonly type: 'array' | 'blocks' | 'group';
694
+ } | {
695
+ readonly hasMany: true;
696
+ };
697
+ type RequiredFields<Fs extends readonly Field[]> = Extract<Visible<Fs>, Present>;
698
+ type OptionalFields<Fs extends readonly Field[]> = Exclude<Visible<Fs>, Present>;
609
699
  /** The shape of the data described by a list of fields. */
610
700
  type FieldsValue<Fs extends readonly Field[], C extends Config = Config> = Simplify<{
611
701
  -readonly [F in RequiredFields<Fs> as F['name']]: FieldValue<F, C>;
@@ -660,7 +750,10 @@ type InputValue<F extends Field> = F extends {
660
750
  }>[] : F extends {
661
751
  readonly type: 'group';
662
752
  readonly fields: infer Sub extends readonly Field[];
663
- } ? FieldsInput<Sub> : FieldValue<F>;
753
+ } ? FieldsInput<Sub> : F extends {
754
+ readonly type: 'blocks';
755
+ readonly blocks: infer B extends readonly Block[];
756
+ } ? readonly BlockInput<B[number]>[] : FieldValue<F>;
664
757
  /** Required fields must be given, unless Easy CMS can fill them (default value, slug from another field). */
665
758
  type NeedsInput<F extends Field> = F extends {
666
759
  readonly required: true;
@@ -761,6 +854,12 @@ interface FindOptions extends ReadOptions {
761
854
  interface CreateEasyCMSOptions {
762
855
  /** Project root. Default `process.cwd()`. */
763
856
  readonly cwd?: string;
857
+ /**
858
+ * Run due scheduled jobs and webhook retries every minute in this process. Default: on when
859
+ * a collection or global has `schedule`, or `webhooks` is set. Turn it off where a cron calls
860
+ * `runJobs` (or `GET <api>/jobs/run`) instead.
861
+ */
862
+ readonly scheduler?: boolean;
764
863
  /** Default `verify` when `NODE_ENV=production`, otherwise `push`. */
765
864
  readonly schema?: SchemaMode;
766
865
  readonly logger?: Logger;
@@ -768,6 +867,16 @@ interface CreateEasyCMSOptions {
768
867
  }
769
868
  /** Connects to the database and returns the Local API. */
770
869
  declare function createEasyCMS<const C extends Config>(config: C, options?: CreateEasyCMSOptions): Promise<EasyCMS<C>>;
870
+ /** A scheduled publish or unpublish. */
871
+ interface ScheduledJob {
872
+ readonly id: ID;
873
+ readonly action: 'publish' | 'unpublish';
874
+ /** ISO time the job runs at (or after). */
875
+ readonly runAt: string;
876
+ readonly state: 'pending' | 'done' | 'failed';
877
+ readonly error: string | null;
878
+ readonly author: ID | null;
879
+ }
771
880
  declare class EasyCMS<C extends Config = Config> {
772
881
  readonly config: ResolvedConfig;
773
882
  readonly db: Database;
@@ -777,6 +886,7 @@ declare class EasyCMS<C extends Config = Config> {
777
886
  /** Where uploaded files are stored. */
778
887
  readonly storage: StorageAdapter;
779
888
  private readonly versions;
889
+ private readonly webhooks;
780
890
  constructor(config: ResolvedConfig, db: Database, logger?: Logger, storage?: StorageAdapter);
781
891
  find<S extends Slug<C>>(collection: S, options?: FindOptions): Promise<PaginatedDocs<Doc<C, S>>>;
782
892
  findById<S extends Slug<C>>(collection: S, id: ID, options?: ReadOptions): Promise<Doc<C, S> | null>;
@@ -875,7 +985,65 @@ declare class EasyCMS<C extends Config = Config> {
875
985
  delete: boolean;
876
986
  }>;
877
987
  /** Closes the database connection. */
988
+ /**
989
+ * Waits until webhook deliveries in progress are done. Call it before a serverless function
990
+ * returns, which may otherwise stop them.
991
+ */
992
+ flushWebhooks(): Promise<void>;
878
993
  destroy(): Promise<void>;
994
+ private schedulerTimer;
995
+ private running;
996
+ /** Runs `runJobs` every `interval` ms in this process (`createEasyCMS` does this by default). */
997
+ startScheduler(interval?: number): void;
998
+ /**
999
+ * Runs due scheduled publishes and unpublishes, and retries failed webhook deliveries. What the
1000
+ * scheduler and the cron endpoint (`GET <api>/jobs/run`) call.
1001
+ */
1002
+ runJobs(now?: Date): Promise<{
1003
+ ran: number;
1004
+ failed: number;
1005
+ webhooks: {
1006
+ sent: number;
1007
+ failed: number;
1008
+ };
1009
+ }>;
1010
+ /**
1011
+ * Tries webhook deliveries that failed earlier and are due for another attempt. Failed
1012
+ * deliveries are kept in the database, so they survive restarts.
1013
+ */
1014
+ retryWebhooks(now?: Date): Promise<{
1015
+ sent: number;
1016
+ failed: number;
1017
+ }>;
1018
+ /** Failed webhook deliveries, stored in `webhook-deliveries`. */
1019
+ private webhookQueue;
1020
+ /**
1021
+ * Publishes or unpublishes documents whose scheduled time has come. Safe to call often, e.g.
1022
+ * from a cron job (`GET <api>/jobs/run`) where no process keeps running.
1023
+ */
1024
+ runScheduled(now?: Date): Promise<{
1025
+ ran: number;
1026
+ failed: number;
1027
+ }>;
1028
+ /** Schedules a publish or unpublish, replacing a pending job with the same action. */
1029
+ schedule<S extends Slug<C>>(collection: S, id: ID, job: {
1030
+ action: 'publish' | 'unpublish';
1031
+ at: Date | string;
1032
+ }, options?: AccessOptions): Promise<ScheduledJob>;
1033
+ /** Pending jobs of a document, soonest first. */
1034
+ scheduled<S extends Slug<C>>(collection: S, id: ID, options?: AccessOptions): Promise<ScheduledJob[]>;
1035
+ cancelSchedule<S extends Slug<C>>(collection: S, id: ID, jobId: ID, options?: AccessOptions): Promise<void>;
1036
+ scheduleGlobal<S extends GSlug<C>>(slug: S, job: {
1037
+ action: 'publish' | 'unpublish';
1038
+ at: Date | string;
1039
+ }, options?: AccessOptions): Promise<ScheduledJob>;
1040
+ scheduledGlobal<S extends GSlug<C>>(slug: S, options?: AccessOptions): Promise<ScheduledJob[]>;
1041
+ cancelGlobalSchedule<S extends GSlug<C>>(slug: S, jobId: ID, options?: AccessOptions): Promise<void>;
1042
+ private scheduleTarget;
1043
+ private globalScheduleTarget;
1044
+ private addJob;
1045
+ private pendingJobs;
1046
+ private removeJob;
879
1047
  /** @internal */
880
1048
  collection(slug: string): CollectionConfig;
881
1049
  private global;
@@ -900,6 +1068,8 @@ declare class EasyCMS<C extends Config = Config> {
900
1068
  private separateDrafts;
901
1069
  /** Replaces published documents that have a newer draft with that draft. */
902
1070
  private withDrafts;
1071
+ /** Sends webhook events for a change; `before` is the stored status before it, if any. */
1072
+ private emit;
903
1073
  /** Records a version after a save, when the collection or global keeps versions. */
904
1074
  private saveVersion;
905
1075
  private hookArgs;
@@ -1161,6 +1331,15 @@ interface AdminField {
1161
1331
  minRows?: number;
1162
1332
  maxRows?: number;
1163
1333
  fields?: AdminField[];
1334
+ /** Block kinds of a `blocks` field. */
1335
+ blocks?: {
1336
+ slug: string;
1337
+ labels?: {
1338
+ singular?: Label;
1339
+ plural?: Label;
1340
+ };
1341
+ fields: AdminField[];
1342
+ }[];
1164
1343
  /** The current user may not change this field. */
1165
1344
  readOnly?: boolean;
1166
1345
  /** One value per content locale. */
@@ -1177,6 +1356,8 @@ interface AdminCollection {
1177
1356
  versions: boolean;
1178
1357
  /** Has live preview (`preview` in the config). */
1179
1358
  preview: boolean;
1359
+ /** Publishing can be scheduled. */
1360
+ schedule: boolean;
1180
1361
  fields: AdminField[];
1181
1362
  permissions: {
1182
1363
  read: boolean;
@@ -1192,6 +1373,8 @@ interface AdminGlobal {
1192
1373
  versions: boolean;
1193
1374
  /** Has live preview (`preview` in the config). */
1194
1375
  preview: boolean;
1376
+ /** Publishing can be scheduled. */
1377
+ schedule: boolean;
1195
1378
  fields: AdminField[];
1196
1379
  permissions: {
1197
1380
  read: boolean;
@@ -1237,4 +1420,4 @@ declare const BUILTIN_COLLECTIONS: readonly ["users", "media"];
1237
1420
  /** Checks a config and returns every problem found. An empty array means it is valid. */
1238
1421
  declare function validateConfig(config: Config): ConfigIssue[];
1239
1422
 
1240
- export { type Access, type AccessArgs, type AccessOptions, type AdminCollection, type AdminConfig, type AdminField, type AdminGlobal, type AdminLocale, type AdminSchema, type AfterChangeHook, type AfterDeleteHook, type AfterReadHook, type ArrayField, Auth, type AuthConfig, type AuthUser, BUILTIN_COLLECTIONS, type BeforeChangeHook, type BeforeDeleteHook, type BeforeValidateHook, type BooleanField, type BuiltinMediaCollection, type BuiltinUsersCollection, type BundleHints, CONFIG_FILE_NAMES, CSRF_COOKIE, CSRF_HEADER, type CollectionAccess, type CollectionConfig, type CollectionDocument, type CollectionHooks, type CollectionSlug, type Config, ConfigError, type ConfigIssue, type CreateEasyCMSOptions, type CreateInput, type CreateMigrationResult, DEFAULT_ADMIN_PATH, DEFAULT_API_PATH, DEFAULT_DEPTH, DEFAULT_MAX_FILE_SIZE, DEFAULT_MAX_VERSIONS, DEFAULT_TOKEN_EXPIRATION, type Database, type DatabaseAdapter, type DatabaseInitArgs, type DateField, type DepthOptions, EXTENSIONS, EasyCMS, EasyCMSError, type EmailField, FIELD_TYPES, type Field, type FieldAccess, type FieldAccessFn, type FieldError, type FieldType, type FieldValidate, type FieldValidateContext, type FieldValue, type FieldsInput, type FieldsValue, type FindArgs, type FindOptions, ForbiddenError, type GlobalAccess, type GlobalConfig, type GlobalDocument, type GlobalHooks, type GlobalInput, type GlobalSlug, type GroupField, type ID, INTERNAL_COLLECTIONS, type ImageSize, type InferCollection, type InferGlobal, type JsonField, type Label, type LivePreview, type LoadConfigOptions, type LocalStorageOptions, type LocalizationConfig, type Logger, type LoginArgs, MAX_DEPTH, MEDIA, MIN_PASSWORD_LENGTH, MIN_SECRET_LENGTH, type MediaDocument, type MediaSize, type MigrationInfo, NotFoundError, type NumberField, type Operation, type PaginatedDocs, PayloadTooLargeError, type Plugin, type PreviewTarget, type PreviewURL, QueryError, type RawDocument, type ReadOptions, type RelationshipField, type ResolvedConfig, type RestHandler, type RestHandlerOptions, type RichTextDocument, type RichTextField, type Role, type RoutesConfig, SESSION_COOKIE, SchemaError, type SchemaMode, type SelectField, type SelectOption, type Session, type SlugField, type StorageAdapter, type StoredFile, type TextField, type TextareaField, TooManyRequestsError, UnauthorizedError, type UpdateInput, type UploadConfig, type UploadField, ValidationError, type Version, type VersionSummary, type VersionsConfig, type Where, type WhereOperators, anyone, applyDefaults, consoleLogger, createEasyCMS, createRestHandler, defineConfig, fillMissing, findConfigFile, generateSlugs, generateTypes, hashPassword, imageDimensions, importConfig, isAdmin, isLoggedIn, loadConfig, localStorage, mergeForUpdate, mimeAllowed, parseId, populate, readCookie, resolveConfig, silentLogger, singularize, slugify, sniffMimeType, validateConfig, validateFields, verifyPassword };
1423
+ export { type Access, type AccessArgs, type AccessOptions, type AdminCollection, type AdminConfig, type AdminField, type AdminGlobal, type AdminLocale, type AdminSchema, type AfterChangeHook, type AfterDeleteHook, type AfterReadHook, type ArrayField, Auth, type AuthConfig, type AuthUser, BUILTIN_COLLECTIONS, type BeforeChangeHook, type BeforeDeleteHook, type BeforeValidateHook, type Block, type BlocksField, type BooleanField, type BuiltinMediaCollection, type BuiltinUsersCollection, type BundleHints, CONFIG_FILE_NAMES, CSRF_COOKIE, CSRF_HEADER, type CollectionAccess, type CollectionConfig, type CollectionDocument, type CollectionHooks, type CollectionSlug, type Config, ConfigError, type ConfigIssue, type CreateEasyCMSOptions, type CreateInput, type CreateMigrationResult, DEFAULT_ADMIN_PATH, DEFAULT_API_PATH, DEFAULT_DEPTH, DEFAULT_MAX_FILE_SIZE, DEFAULT_MAX_VERSIONS, DEFAULT_TOKEN_EXPIRATION, type Database, type DatabaseAdapter, type DatabaseInitArgs, type DateField, type DepthOptions, EXTENSIONS, EasyCMS, EasyCMSError, type EmailField, FIELD_TYPES, type Field, type FieldAccess, type FieldAccessFn, type FieldError, type FieldType, type FieldValidate, type FieldValidateContext, type FieldValue, type FieldsInput, type FieldsValue, type FindArgs, type FindOptions, ForbiddenError, type GlobalAccess, type GlobalConfig, type GlobalDocument, type GlobalHooks, type GlobalInput, type GlobalSlug, type GroupField, type ID, INTERNAL_COLLECTIONS, type ImageSize, type InferCollection, type InferGlobal, type JsonField, type Label, type LivePreview, type LoadConfigOptions, type LocalStorageOptions, type LocalizationConfig, type Logger, type LoginArgs, MAX_DEPTH, MEDIA, MIN_PASSWORD_LENGTH, MIN_SECRET_LENGTH, type MediaDocument, type MediaSize, type MigrationInfo, NotFoundError, type NumberField, type Operation, type PaginatedDocs, PayloadTooLargeError, type Plugin, type PreviewTarget, type PreviewURL, QueryError, type RawDocument, type ReadOptions, type RelationshipField, type ResolvedConfig, type RestHandler, type RestHandlerOptions, type RichTextDocument, type RichTextField, type Role, type RoutesConfig, SESSION_COOKIE, type ScheduledJob, SchemaError, type SchemaMode, type SelectField, type SelectOption, type Session, type SlugField, type StorageAdapter, type StoredFile, type TextField, type TextareaField, TooManyRequestsError, UnauthorizedError, type UpdateInput, type UploadConfig, type UploadField, ValidationError, type Version, type VersionSummary, type VersionsConfig, WEBHOOK_EVENTS, type WebhookConfig, type WebhookEvent, type WebhookPayload, type Where, type WhereOperators, anyone, applyDefaults, consoleLogger, createEasyCMS, createRestHandler, defineConfig, fillMissing, findConfigFile, generateSlugs, generateTypes, hasRows, hashPassword, imageDimensions, importConfig, isAdmin, isLoggedIn, loadConfig, localStorage, mergeForUpdate, mimeAllowed, parseId, populate, readCookie, resolveConfig, rowFields, silentLogger, singularize, slugify, sniffMimeType, validateConfig, validateFields, verifyPassword };