@diagonal-hq/cli 0.32.2 → 0.33.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.
package/README.md CHANGED
@@ -2,14 +2,13 @@
2
2
 
3
3
  This package is the authoring SDK for file-based workspaces. A workspace repository installs it as a dev dependency. It gives these things:
4
4
 
5
- - The configuration helpers: `defineConfig`, `defineResource`, `definePage`, `text.template`, `defineAssets`, `asset.version`, `defineRedirects`, `defineNotificationType`, `defineNotificationTemplate`, `defineEmailLayout`, `defineNotificationSchedule`, and the `field` builders. Each `define*` function returns its first argument. Each `field.<type>(options)` call returns `{ $field, ...options }`, where `$field` is the stored field type. The package root exports them as ESM JavaScript with declarations, so a Vite build or a Node script can import a configuration file.
5
+ - The configuration helpers: `defineConfig`, `defineResource`, `definePolicy`, `defineRecord`, `definePage`, `text.template`, `defineAssets`, `asset.version`, `defineRedirects`, `defineNotificationType`, `defineNotificationTemplate`, `defineEmailLayout`, `defineNotificationSchedule`, and the `field` builders. Each `define*` function returns its first argument. Each `field.<type>(options)` call returns `{ $field, ...options }`, where `$field` is the stored field type. The package root exports them as ESM JavaScript with declarations, so a Vite build or a Node script can import a configuration file.
6
6
  - Types for the helpers, `WorkflowConfig`, and the `Sdk` and `React` globals.
7
7
  - Editor types for the workflow script SDK: `@diagonal/workflow`, `@diagonal/workflow/testing`, and `@diagonal/workflow/workspace`.
8
8
  - The `diagonal check` command. It runs the same build and checks that a platform deploy runs, including the workflow tests. It also writes `generated/resources.ts`, `generated/pages.ts`, `generated/workflows.ts`, `generated/assets.ts`, `generated/catalog.d.ts`, and the missing definition uids.
9
9
  - The `diagonal make:migration <name>` command. It creates an ordinary workflow in `migrations/` with a timestamped filename. Every migration runs as system.
10
10
  - The `diagonal assets upload` and `diagonal assets list` commands. They upload Application Assets, update `assets.ts`, and list immutable references.
11
11
  - The `diagonal workflows`, `diagonal run`, and `diagonal logs` commands. They list the deployed workflows, run a manual workflow by its file path, and print recent runs with the error of each failed run.
12
- - The `diagonal git setup` and `diagonal merge-driver` commands. They merge resource files entry by entry in a git merge.
13
12
 
14
13
  ## Check a workspace
15
14
 
@@ -40,28 +39,6 @@ diagonal make:migration backfill_post_slug
40
39
 
41
40
  The command creates `migrations/YYYYMMDDHHmmss_backfill_post_slug.ts` with the current timestamp. In a workspace template, run `npm run migration -- backfill_post_slug` for the same result. Edit the generated workflow, then run `diagonal check` before committing. Keep deployed files unchanged. Use a new migration filename for a correction.
42
41
 
43
- ## Merge resource files
44
-
45
- Git merges a file line by line. When two branches each add a field, a record, or a policy to one resource, git can report a conflict that does not exist. The `diagonal-resource` merge driver merges each `resources/<name>.ts` file entry by entry. Run this command once in each clone:
46
-
47
- ```bash
48
- npx diagonal git setup
49
- ```
50
-
51
- The command registers the driver in the local git config. It also adds `resources/*.ts merge=diagonal-resource` to `.gitattributes` when the line is missing. A new workspace repository has this line already. Commit `.gitattributes`.
52
-
53
- The driver compares each entry of the three versions: the base, your branch, and the other branch.
54
-
55
- - `fields` and `records` merge by key.
56
- - An array of objects with a string `uid`, such as `policies`, merges by uid.
57
- - An array of string literals, such as `fieldOrder`, keeps the additions and removals of both branches.
58
- - Each other option, and the code around `defineResource()`, merges as one value.
59
- - A difference in whitespace or trailing commas is not a change.
60
-
61
- When both branches change one entry differently, or one branch deletes an entry that the other changes, the entry is a conflict. The driver writes diff3 markers around that entry only, with the labels `branch`, `base`, and `main`. Resolve the markers, then run `diagonal check`. When the driver cannot read a file, git's line merge with diff3 markers runs instead.
62
-
63
- Git starts the driver as `diagonal merge-driver %O %A %B %P`. The command exits with 0 when the merge has no conflict and with 1 when it has a conflict.
64
-
65
42
  ## Workspace API credentials
66
43
 
67
44
  The API commands read `DIAGONAL_URL` and `DIAGONAL_API_KEY`. Workflow commands require `manage_workflows`. Asset commands require `manage_workspace_settings`. A System Administrator has both permissions. Keep API keys out of the repository.
@@ -90,13 +67,13 @@ diagonal logs [path | execution id] [--status <status>] [--limit <1-100>] [--jso
90
67
 
91
68
  The build reads each file with a parser. It runs only the workflow and migration tests.
92
69
 
93
- - `defineConfig`, `defineResource`, and the first argument of `definePage` must be static literals. `diagonal.config.ts` goes through the checks in [Workspace config](#workspace-config). The `field.<type>({...})` calls are the only calls that the build accepts in this data. The `seo` values of a page are the one exception: a `seo` value can be a one-expression function. See [Page bindings and seo](#page-bindings-and-seo).
94
- - Each `resources/*.ts` file goes through the resource checks in [Resources and fields](#resources-and-fields).
95
- - The build removes imports from `@diagonal-hq/cli`. Pages, layouts, components, and workflow scripts can import workspace files through `@app/`. A resource file can import only `@app/generated/resources`, `@app/generated/pages`, and `@app/generated/record-bindings`. A notification type, template, or schedule file can import only `@app/generated/resources`, `@app/generated/notification-types`, `@app/generated/email-layouts`, and `@app/generated/record-bindings`, and an email layout file only `@app/generated/resources` and `@app/generated/record-bindings`. `diagonal.config.ts` and each `workspace-fields/` file can also import `@app/generated/record-bindings`. Write `RecordBindings.<Name>.reference` from that module where a value needs a live record ID that each workspace selects. Workflow scripts can also import `@diagonal/workflow` and `@diagonal/workflow/workspace`. Other external imports in these source files are rejected.
70
+ - `defineConfig`, `defineResource`, `definePolicy`, `defineRecord`, and the first argument of `definePage` must be static literals. `diagonal.config.ts` goes through the checks in [Workspace config](#workspace-config). The `field.<type>({...})` calls are the only calls that the build accepts in this data. The `seo` values of a page are the one exception: a `seo` value can be a one-expression function. See [Page bindings and seo](#page-bindings-and-seo).
71
+ - Each resource folder, `resources/<folder>/`, goes through the resource checks in [Resources and fields](#resources-and-fields).
72
+ - The build removes imports from `@diagonal-hq/cli`. Pages, layouts, components, and workflow scripts can import workspace files through `@app/`. A `resource.ts`, field, policy, or record file can import only `@app/generated/resources`, `@app/generated/pages`, and `@app/generated/record-bindings`. A notification type, template, or schedule file can import only `@app/generated/resources`, `@app/generated/notification-types`, `@app/generated/email-layouts`, and `@app/generated/record-bindings`, and an email layout file only `@app/generated/resources` and `@app/generated/record-bindings`. `diagonal.config.ts` and each `workspace-fields/` file can also import `@app/generated/record-bindings`. Write `RecordBindings.<Name>.reference` from that module where a value needs a live record ID that each workspace selects. Workflow scripts can also import `@diagonal/workflow` and `@diagonal/workflow/workspace`. Other external imports in these source files are rejected.
96
73
  - The second argument of `definePage`, and the default export of a layout or component file, must be one function. A page imports a layout and passes it as `layout: AppLayout`, and imports a component and renders it as `<ClassCard />`. A string `layout` and `Sdk.Custom.<Name>` fail with the import to write. A component is any `.tsx` module that a page or layout reaches and that default-exports a PascalCase function, directly or as `export default Name` for a `const` function or arrow function of the file. It can also have named exports. It gets the page lint and type check at its own path.
97
74
  - Each page has one name: the studly case of each folder and file name below `pages/`, joined with `_`, without `.tsx`. A route parameter segment such as `[id]` gets the prefix `$`. `pages/sign-in.tsx` is `Pages.SignIn`, `pages/members/[id].tsx` is `Pages.Members_$Id`, `pages/index.tsx` is `Pages.Index`, and `pages/classes/index.tsx` is `Pages.Classes_Index`. A name that starts with a digit gets the prefix `Page`, so `pages/404.tsx` is `Pages.Page404`. Two page files with one name, such as `pages/members-list.tsx` and `pages/members_list.tsx`, fail at the second file: `The page files A and B both have the name Pages.Members_$Id. Rename one of the files`. `definePage` has no `key` option. The check refuses it with `Unknown page option "key"`.
98
75
  - Each page also has a `uid`. See [Definition uids and slugs](#definition-uids-and-slugs). The uid is the identity of the page. A file move or rename changes the page name, but the uid stays. Settings that store the uid still resolve. Resource capability settings name a page by this uid.
99
- - Every file that names a page imports `Pages` from `@app/generated/pages`: `diagonal.config.ts`, resource files, pages, layouts, components, and menus. There is one `Pages` object. `Pages` is not a global, and `@diagonal-hq/pages` does not export it. A file that uses `Pages` without the import fails the check with `'Pages' is not defined`. Every file names a page by its uid, `Pages.<Name>.uid`, as it names a workflow by `Workflows.<Name>.slug`. Pages, layouts, and components pass the uid to `utils` from `@diagonal-hq/pages`: `utils.page.url(Pages.Members.uid)`, `utils.page.url(Pages.Members_$Id.uid, { id })`, `utils.page.navigate(Pages.Members.uid)`, and `utils.page.navigate(Pages.Members_$Id.uid, { id }, { openInNewTab: true })`. A menu item is `{ kind: 'page', label, page: Pages.Members.uid }`. A config or resource file names a page with `Pages.<Name>.uid` too. See [Page reference settings](#page-reference-settings). The check fails at an unknown name, such as a stale name after a file move: `Unknown page "Pages.X". Each name in Pages is a file in pages/`. The type check also fails at a call without the route parameters of the page, at route parameters for a page without any, and at a menu item for a page with route parameters. The error names the page and its route, such as `Pages.Members_$Id has the route /members/{id}. Pass its route parameters as params.`
76
+ - Every file that names a page imports `Pages` from `@app/generated/pages`: `diagonal.config.ts`, `resource.ts` files, pages, layouts, components, and menus. There is one `Pages` object. `Pages` is not a global, and `@diagonal-hq/pages` does not export it. A file that uses `Pages` without the import fails the check with `'Pages' is not defined`. Every file names a page by its uid, `Pages.<Name>.uid`, as it names a workflow by `Workflows.<Name>.slug`. Pages, layouts, and components pass the uid to `utils` from `@diagonal-hq/pages`: `utils.page.url(Pages.Members.uid)`, `utils.page.url(Pages.Members_$Id.uid, { id })`, `utils.page.navigate(Pages.Members.uid)`, and `utils.page.navigate(Pages.Members_$Id.uid, { id }, { openInNewTab: true })`. A menu item is `{ kind: 'page', label, page: Pages.Members.uid }`. A config or resource file names a page with `Pages.<Name>.uid` too. See [Page reference settings](#page-reference-settings). The check fails at an unknown name, such as a stale name after a file move: `Unknown page "Pages.X". Each name in Pages is a file in pages/`. The type check also fails at a call without the route parameters of the page, at route parameters for a page without any, and at a menu item for a page with route parameters. The error names the page and its route, such as `Pages.Members_$Id has the route /members/{id}. Pass its route parameters as params.`
100
77
  - Pages, layouts, and components go through the page lint gate: syntax, scope, the component return shape, and a type check against the page Sdk contract and the workspace resources. A page imports the Page SDK members that it uses from `@diagonal-hq/pages`, such as `import { resource, useRecords } from '@diagonal-hq/pages'`. A page names a resource by slug, for example `resource(Resources.Members.slug)`.
101
78
  - Each `workflows/<name>.ts` is a script workflow. Its default export is `defineWorkflow({ uid, name, trigger, runAs?, input?, validate? }, handler)` from `@diagonal/workflow`, the same shape as `definePage(options, component)`. The config is the first argument and must be an object literal. The build reads every option except `input` and `validate` as static data and never runs the handler to find it. `input` is a `v.object({...})` schema, or a top-level `const` of one, which the script compiler reads. `validate` is a function that runs after the input check and before the handler, with the same input type. It returns errors keyed by field, and any error ends the run with a 422. The editor checks the config against `WorkflowConfig` from `@diagonal-hq/cli`. The build validates it: the uid (see [Definition uids and slugs](#definition-uids-and-slugs)), the trigger fields, the resources (see [Resource references](#resource-references)), the workflow references of `workflowEvent` triggers (see [Workflow references](#workflow-references)), the filter tree of a `recordEvent` trigger's `filters` (see [Policies](#policies)), and the run-as rules. A `recordEvent`, `recordSchedule`, `scheduled`, or `workflowEvent` workflow needs `runAs`.
102
79
  - A `recordSchedule` trigger runs each offset from the `dateField` of each record. `timing` defaults to `'day'`, which runs at 8 a.m. in the workspace timezone on the day of the field plus the offset, and ignores the time of the field. Day timing takes whole-day offsets only, so the build refuses an offset such as `'-PT2H'` or `'+PT0M'`. `timing: 'exact'` runs at the time of the field plus the offset, for example 2 hours before a class with `offsets: ['-PT2H']`. Exact timing needs a datetime field.
@@ -115,11 +92,11 @@ The build reads each file with a parser. It runs only the workflow and migration
115
92
  A definition can have two identity options. A resource, a field, a relation inverse, a policy, a static record, a permission, a role, a page, a workflow config, a notification type, a notification template, an email layout, a workspace field, the front matter of a skill file, and a layout or component module in `layouts/` or `components/` have a `uid`. A resource, a permission, a role, a workflow, a notification type, a notification template, and an email layout also have a `slug`. A workspace field has a `key` in the place of a `slug`.
116
93
 
117
94
  - `uid` is the stable identity of the definition. Its value is a lowercase UUID string literal, such as `uid: '019a4d6e-3c2f-7b8a-9d1e-5f6a7b8c9d0e'`. In skill front matter, it is a YAML string, such as `uid: 019a4d6e-3c2f-7b8a-9d1e-5f6a7b8c9d0e`. A layout or component module exports it after its imports, such as `export const uid = '019a4d6e-3c2f-7b8a-9d1e-5f6a7b8c9d0e';`. It identifies the module's shared draft in the platform. A layout or component without a uid still builds. A file move, a file rename, or a name change keeps the uid. The deploy keeps the stored id of a resource, a field, a page, a workflow, a workspace field, and a skill by its uid, so these changes keep the definition's records, runs, and references. Do not change a uid: a new uid is a new definition.
118
- - `slug` is the editable, user-facing name of the definition. It is an optional string literal in the `defineX()` call, which is the config of `defineWorkflow(config, handler)` for a workflow. Without it, the path gives the slug: the file name of a resource, a permission, a role, a workflow, or a template, and the folder name of a notification type or an email layout. A `slug` can differ from the path, and a file rename then keeps the slug. A slug change keeps the uid.
95
+ - `slug` is the editable, user-facing name of the definition. It is an optional string literal in the `defineX()` call, which is the config of `defineWorkflow(config, handler)` for a workflow. Without it, the path gives the slug: the file name of a permission, a role, a workflow, or a template, and the folder name of a resource, a notification type, or an email layout. A `slug` can differ from the path, and a file rename then keeps the slug. A slug change keeps the uid.
119
96
 
120
97
  | Definition | Path | Slug without a `slug` option | Rule of the slug |
121
98
  | --------------------- | ------------------------------------------- | ------------------------------------ | ----------------------------------------------------------------------------------------------- |
122
- | Resource | `resources/<file>.ts` | The file name | Starts with a lowercase letter and contains only a-z, 0-9, `_`, and `-` |
99
+ | Resource | `resources/<folder>/resource.ts` | The folder name | Starts with a lowercase letter and contains only a-z, 0-9, `_`, and `-` |
123
100
  | Permission | `permissions/<file>.ts` | The file name | Starts with a lowercase letter, contains only a-z, 0-9, and `_`, and has at most 255 characters |
124
101
  | Role | `roles/<file>.ts` | The file name | The rule of a permission slug |
125
102
  | Workflow | `workflows/<file>.ts` | The file name | The rule of a resource slug, for a `slug` option |
@@ -128,11 +105,11 @@ A definition can have two identity options. A resource, a field, a relation inve
128
105
  | Email layout | `email-layouts/<folder>/layout.ts` | The folder name | The rule of a notification type slug, and not `default` |
129
106
  | Workspace field | `workspace-fields/<file>.ts` | The file name, as the `key` | Starts with a lowercase letter and contains only a-z, 0-9, and `_` |
130
107
 
131
- The path also gives the name of the definition in its generated module, such as `Resources.JobPostings` for `resources/job-postings.ts`. A `slug` option does not change that name: `.slug` of the entry holds the slug. So the file name follows the rule of its slug too, as a folder name does. A `slug` must be a string literal, because the build reads each slug before it builds the files. Two definitions of one kind with one slug are an error at the second file. A template slug is unique among the templates of its type. A migration has no `slug`: its file name is its identity.
108
+ The path also gives the name of the definition in its generated module, such as `Resources.JobPostings` for `resources/job-postings/resource.ts`. A `slug` option does not change that name: `.slug` of the entry holds the slug. So the file name follows the rule of its slug too, as a folder name does. A `slug` must be a string literal, because the build reads each slug before it builds the files. Two definitions of one kind with one slug are an error at the second file. A template slug is unique among the templates of its type. A migration has no `slug`: its file name is its identity.
132
109
 
133
110
  A setting that names another definition takes the `uid` of its generated entry, for example `NotificationTypes.MemberWelcome.uid`, `NotificationTypes.MemberWelcome.templates.Standard.uid`, `EmailLayouts.Standard.uid`, `Workflows.BookClass.uid`, `Permissions.ManageBookings.uid`, or `Pages.Home.uid`. The uid survives a rename, and the platform finds the definition from it. A notification send, a schedule, `defaultTemplate`, a template layout, a page workflow call, and `ctx.can` also take a slug, as a string or as a `.slug` member. It builds and runs, with a warning that names the `.uid` reference. A workflow path, such as `'workflows/add.ts'`, is an error in every workflow reference: a `workflowEvent` trigger, `workflow.run`, and page code. A resource is the exception: a setting names it with `Resources.<Name>.slug`. A domain and an Application Asset have no uid, so a setting names them with `.key`. A workspace field has a uid, but code reads its value by key, so a setting names it with `WorkspaceFields.<Name>.key`.
134
111
 
135
- `diagonal check` writes a new uid into each definition that has none. It adds `uid: '<uuid>'` as the first option of the `defineX()` object, of each `field.<type>({...})` call, `settings.inverse` object, and policy, or of the config object of `defineWorkflow(config, handler)`, `uid: <uuid>` as the first line of the front matter of a skill file, or `export const uid = '<uuid>';` after the imports of a layout or component module, and leaves the rest of the file unchanged. Commit the change.
112
+ `diagonal check` writes a new uid into each definition that has none. It adds `uid: '<uuid>'` as the first option of the `defineX()` object, such as the `definePolicy()` object of a policy file and the `defineRecord()` object of a record file, of each `field.<type>({...})` call of a field file and its `settings.inverse` object, or of the config object of `defineWorkflow(config, handler)`, `uid: <uuid>` as the first line of the front matter of a skill file, or `export const uid = '<uuid>';` after the imports of a layout or component module, and leaves the rest of the file unchanged. Commit the change.
136
113
 
137
114
  The platform writes the missing uids too: a save in Files, and every other commit that the platform makes, adds a uid to each definition of the changed files that has none. A git push does not, so a pushed definition without a uid fails the deploy, and the error tells you to run `diagonal check`.
138
115
 
@@ -381,9 +358,9 @@ const frontDesk = await workspace.value({ key: WorkspaceFields.FrontDeskEmail.ke
381
358
 
382
359
  ## Resource references
383
360
 
384
- The file name is the resource slug: `resources/job-postings.ts` declares the resource `job-postings`. A `slug` option replaces it, so `defineResource({ slug: 'jobs', ... })` in `resources/job-postings.ts` declares the resource `jobs`. See [Definition uids and slugs](#definition-uids-and-slugs). A file name and a slug must start with a lowercase letter and contain only a-z, 0-9, `_`, and `-`. A resource has no `id` in source. Each resource file has a `uid`, which the deploy stores on the resource. A resource keeps the id that the workspace stores for its uid, so a renamed file keeps its id and its records. Each field keeps its id the same way, through its `uid`. A new resource gets an id from the workspace and the uid, so each branch and environment has its own ids.
361
+ The folder name is the resource slug: `resources/job-postings/resource.ts` declares the resource `job-postings`. A `slug` option replaces it, so `defineResource({ slug: 'jobs', ... })` in `resources/job-postings/resource.ts` declares the resource `jobs`. See [Definition uids and slugs](#definition-uids-and-slugs). A folder name and a slug must start with a lowercase letter and contain only a-z, 0-9, `_`, and `-`. A resource has no `id` in source. Each `resource.ts` has a `uid`, which the deploy stores on the resource. A resource keeps the id that the workspace stores for its uid, so a renamed folder keeps its id and its records. Each field keeps its id the same way, through its `uid`. A new resource gets an id from the workspace and the uid, so each branch and environment has its own ids.
385
362
 
386
- The build writes `generated/resources.ts` from the resource files and the built-in resources. `diagonal check` writes it on your machine, so the editor knows the types of `Resources`. The file is a build output: the workspace `.gitignore` lists it, and a deploy writes its own copy.
363
+ The build writes `generated/resources.ts` from the resource folders and the built-in resources. `diagonal check` writes it on your machine, so the editor knows the types of `Resources`. The file is a build output: the workspace `.gitignore` lists it, and a deploy writes its own copy.
387
364
 
388
365
  The build also writes `generated/catalog.d.ts`: the record type of each resource and the route parameters of each page uid, added to the types of `@diagonal-hq/pages`. The workspace `tsconfig.json` includes it, so your editor and `tsc` type `useRecords(Resources.<Name>.slug)` as `diagonal check` does: `classes.data[0]?.title` has the field's type, and an unknown field is an error. `utils.page.url(Pages.<Name>.uid)` requires the route parameters of the page. Run `diagonal check` after you change a resource or a page, so the file follows it.
389
366
 
@@ -398,7 +375,7 @@ export const Resources = {
398
375
  displayField: 'name',
399
376
  fields: {
400
377
  plan: {
401
- uid: 'b19d0865-cd0e-44ff-9f34-f4b73dabdd50',
378
+ uid: '01a1d9ed-c20e-7d48-a543-5fe8adc4f5c5',
402
379
  key: 'plan',
403
380
  type: 'select',
404
381
  label: 'Plan',
@@ -422,15 +399,15 @@ export const Resources = {
422
399
  } as const;
423
400
  ```
424
401
 
425
- Each property is the studly case of a file name. Its value is the metadata that the resource file declares: the uid, the slug, the name, the singular name, the display field, and for each field its uid, key, type, label, description, and required flag, with the options of a select field and the target slug of a relation field. `policies` holds the uid and the name of each policy, keyed by the studly case of its name, so the policy "Staff only" is `Resources.<Name>.policies.StaffOnly`. A key that starts with a digit gets the prefix `Policy`. A policy name is only a label, so when two policies of one resource have one key, the first keeps it, and the second gets no key and a warning. A name without letters or digits gives no key and a warning. The entry holds no policy rules: no scope, access, filter, or fields. `Resources` holds no capabilities, indexes, or field guards and setters. Two file names with the same name, such as `job-postings` and `job_postings`, are an error, and so are two resource files with one slug.
402
+ Each property is the studly case of a folder name. Its value is the metadata that the resource folder declares: the uid, the slug, the name, the singular name, the display field, and for each field its uid, key, type, label, description, and required flag, with the options of a select field and the target slug of a relation field. `policies` holds the uid and the name of each policy, keyed by the studly case of its file name, so `policies/staff_only.ts` is `Resources.<Name>.policies.StaffOnly`. A key that starts with a digit gets the prefix `Policy`. When two file names of one resource have one key, such as `staff_only.ts` and `staffonly.ts`, the first path keeps it, and the second policy gets no key and a warning. A file name without letters or digits gives no key and a warning. The entry holds no policy rules: no scope, access, filter, or fields. `Resources` holds no capabilities, indexes, or field guards and setters. Two folder names with the same name, such as `job-postings` and `job_postings`, are an error, and so are two resources with one slug.
426
403
 
427
404
  Name a resource with `Resources.<Name>.slug` from `@app/generated/resources` everywhere: `field.relation({ resource: Resources.User.slug })`, a workflow `trigger.resource` and `runAs.resource`, a page `authorizer.resource` and `bindings.<name>.resource`, `resource(Resources.User.slug)` from `@diagonal-hq/pages`, `data.search({ resource: Resources.User.slug })`, and `v.record(Resources.User.slug)`. The build reads `Resources.<Name>.slug` like a literal. An unknown name is an error at its location, and the editor reports it too. A bare `Resources.User` in one of these places is an error.
428
405
 
429
406
  Read the other metadata in pages and workflows, for example `Resources.User.name`, `Resources.User.uid`, `Resources.User.fields.plan.uid`, or `Resources.User.fields.plan.options`. Each value has its literal type. The build replaces each such reference with its value, so a page carries only the metadata that it reads, and a compiled workflow changes only when a value that it reads changes. A page cannot use `Resources` as a whole, for example in `Object.keys(Resources)`, or re-export it.
430
407
 
431
- A slug string, such as `resource: 'user'`, builds with a warning. A resource id, a resource name, a singular name, or a slug without a file is an error.
408
+ A slug string, such as `resource: 'user'`, builds with a warning. A resource id, a resource name, a singular name, or a slug without a resource folder is an error.
432
409
 
433
- `Resources.Roles` and `Resources.Permissions` are built in: the build always generates them, with only their `slug`, and they have no resource file. The deploy maps each one to the Roles or Permissions resource of the workspace, and writes their records from `roles/` and `permissions/`, see [Permissions](#permissions) and [Roles](#roles). The build does not know their fields, so a data call types their records loosely, and a relation to them cannot declare an inverse. A file `resources/roles.ts` or `resources/permissions.ts` is an error: delete it. A `slug` option of `roles` or `permissions` is an error too. A `defineResource({ platform: true })` file is an error too: declare the resource with its fields, or delete the file.
410
+ `Resources.Roles` and `Resources.Permissions` are built in: the build always generates them, with only their `slug`, and they have no resource folder. The deploy maps each one to the Roles or Permissions resource of the workspace, and writes their records from `roles/` and `permissions/`, see [Permissions](#permissions) and [Roles](#roles). The build does not know their fields, so a data call types their records loosely, and a relation to them cannot declare an inverse. A folder `resources/roles/` or `resources/permissions/` is an error: delete it. A `slug` option of `roles` or `permissions` is an error too. A `defineResource({ platform: true })` file is an error too: declare the resource with its fields, or delete the file.
434
411
 
435
412
  ## Permissions
436
413
 
@@ -481,7 +458,7 @@ The deploy writes every system permission and each permission of `permissions/`
481
458
 
482
459
  The first deploy of a workspace matches each seeded system permission by its slug. It changes the id of the stored record to the uid and rewrites the role grants, so the roles keep their permissions. The deploy does not take over a custom permission that the workspace created. A declared permission whose slug a stored record already has blocks the deploy: delete that record, or remove the declaration. A stored custom permission that `permissions/` does not declare also blocks that deploy: declare it with its current record id as its `uid`, or delete it first. To get the record id, open the actions of the permission in the Security admin and select **Copy Permission ID**. Declare the permission with that `uid` in the file of its current slug, so it keeps its id and its role grants. Do not let `diagonal check` generate a new uid for it, because a new uid blocks the deploy.
483
460
 
484
- A new repository declares its staff resource in a resource file, such as `resources/staff.ts`, with fields and the Authenticatable capability. The deploy owns that resource like any other resource file. Name it in `diagonal.config.ts` with `staffResource: { resource: Resources.Staff.slug }`. The build refuses a `staffResource` that is not an Authenticatable resource file. After the first deploy, the platform adds the default administrator to that resource.
461
+ A new repository declares its staff resource in a resource folder, such as `resources/staff/`, with field files and the Authenticatable capability in `resource.ts`. The deploy owns that resource like any other resource. Name it in `diagonal.config.ts` with `staffResource: { resource: Resources.Staff.slug }`. The build refuses a `staffResource` that is not an Authenticatable resource of the files. After the first deploy, the platform adds the default administrator to that resource.
485
462
 
486
463
  ## Roles
487
464
 
@@ -775,17 +752,64 @@ Fixtures are sample data for previews. They are not tests, and they are never se
775
752
 
776
753
  ## Resources and fields
777
754
 
778
- `defineResource` takes `name`, `singularName`, `displayField`, `searchableFields`, `fieldOrder`, `fields`, `indexes`, `embeddings`, `dataApi`, `static`, `records`, `policies`, and `capabilities`. The build refuses an unknown property, an unknown setting, and a duplicate key, and gives the line and column. It does not remove anything without a diagnostic.
755
+ A resource is a folder of `resources/`. The folder name is the slug of a resource without a `slug` option, and it gives the name in `Resources`.
756
+
757
+ | Path | Content |
758
+ | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
759
+ | `resources/<folder>/resource.ts` | `export default defineResource<'<folder>'>({...})`: the settings of the resource |
760
+ | `resources/<folder>/fields/<key>.ts` | `export default field.<type>({...})`: one field. The file name is the field key |
761
+ | `resources/<folder>/policies/<key>.ts` | `export default definePolicy<'<folder>'>({...})`: one policy. See [Policies](#policies) |
762
+ | `resources/<folder>/records/<key>.ts` | `export default defineRecord<'<folder>'>({...})`: one record of a static resource. The file name is the record key |
763
+
764
+ Each field, policy, and record is a file of its own, so two branches that change different entries change different files, and git merges them without a conflict.
765
+
766
+ - A field, policy, or record file whose folder has no `resource.ts` is an error.
767
+ - An old `resources/<name>.ts` file is an error: `A resource is a folder. Move the settings of this file to resources/<name>/resource.ts, and each field, policy, and record to a file of its own in resources/<name>/fields/, policies/, and records/`.
768
+ - A diagnostic for a field, a policy, or a record names its file.
769
+ - Give the folder as the type argument of the define call, such as `defineResource<'rooms'>({...})`, `definePolicy<'rooms'>({...})`, and `defineRecord<'rooms'>({...})`. Then the editor checks the field keys and field types of the settings, the policy `fields`, the capability settings, and the record values against the resource. `diagonal check` writes `generated/resource-folders.ts`, which holds the fields of each folder. Without the argument, the keys are open strings. The build checks the keys either way. A type argument that names another folder, as after a rename of the folder, gives a warning with the call to write. The app writes the argument in each file that it creates or changes.
770
+
771
+ `defineResource` takes `uid`, `slug`, `name`, `singularName`, `displayField`, `searchableFields`, `fieldOrder`, `indexes`, `embeddings`, `dataApi`, `static`, and `capabilities`. It refuses `fields`, `policies`, and `records` with a message that names the file to write, for example `Remove "fields" from resource.ts. Move each field to fields/<key>.ts in the folder of the resource, as export default field.<type>({...})`. The build refuses an unknown property, an unknown setting, and a duplicate key, and gives the line and column. It does not remove anything without a diagnostic.
772
+
773
+ ```ts
774
+ // resources/rooms/resource.ts
775
+ import { defineResource } from '@diagonal-hq/cli';
776
+
777
+ export default defineResource<'rooms'>({
778
+ uid: '55c87b3e-6e93-4907-ae4d-bf6d166e5c85',
779
+ name: 'Rooms',
780
+ singularName: 'Room',
781
+ displayField: 'name',
782
+ fieldOrder: ['name'],
783
+ static: true
784
+ });
785
+ ```
786
+
787
+ ```ts
788
+ // resources/rooms/fields/name.ts
789
+ import { field } from '@diagonal-hq/cli';
790
+
791
+ export default field.text({ label: 'Name', required: true });
792
+ ```
793
+
794
+ ```ts
795
+ // resources/rooms/records/studio_a.ts
796
+ import { defineRecord } from '@diagonal-hq/cli';
797
+
798
+ export default defineRecord<'rooms'>({
799
+ uid: '01a1a84a-78f3-78dc-8633-008e506ce4f6',
800
+ name: 'Studio A'
801
+ });
802
+ ```
779
803
 
780
804
  - `searchableFields` lists the field keys and relation paths that record search matches, for example `['title', 'author.full_name']`. The build checks each path against the related resources. Without it, search matches the display field and every text and markdown field.
781
- - `fieldOrder` lists every field key once. It sets the order of the fields in forms and tables. The default is the order of `fields`.
805
+ - `fieldOrder` is a partial list of field keys. Forms and tables show the listed fields first, in list order. The other fields follow in uid order, which is the order in which they were made, because a uid is a UUID version 7. A field without a uid comes last, by key. A key that is not a field of the resource is an error, and so is a key that the list has twice. A new field does not change `fieldOrder`, so two branches that each add a field do not conflict. A reorder in the resource builder writes the complete list, and a field delete removes its key.
782
806
  - `embeddings` is `{ enabled, fields }`. `fields` names fields of the resource, not relation paths.
783
807
  - `dataApi.endpoints` turns off data API endpoints, for example `{ delete_many: { enabled: false } }`. An omitted endpoint stays enabled.
784
- - `static: true` makes the resource a fixed set of records. `records` declares every record by key, for example `{ standard: { uid: '019a…', name: 'Standard' } }`, and `records: {}` declares none. `diagonal check` writes each record's `uid`, a UUID version 7 that is the record id in every environment. The deploy writes the records, and normal record writes to the resource are refused. `Resources.<Name>.records.<key>` holds the record's `uid` and the value of each field, for example `Resources.Rooms.records.studio_a.name`. A page that reads a value sends it to every viewer. A static resource has no capabilities. It can have a `belongs_to` or `belongs_to_many` relation only to another static resource, because the relation is stored on its records. A record sets that relation with the `uid` of a target record, or a list of uids for `belongs_to_many`, and the build checks each uid. The deploy writes the target records first, so the build refuses a cycle of these relations, and a relation of a static resource to itself.
808
+ - `static: true` makes the resource a fixed set of records. Each record is a file `records/<key>.ts` of the folder, `export default defineRecord({ uid, ...values })`, for example `defineRecord({ uid: '019a…', name: 'Standard' })` in `records/standard.ts`. A static resource without records needs no record file. A record file in the folder of a resource that is not static is an error, and a record value cannot have the key `uid`. `diagonal check` writes each record's `uid`, a UUID version 7 that is the record id in every environment. The deploy writes the records, and normal record writes to the resource are refused. `Resources.<Name>.records.<key>` holds the record's `uid` and the value of each field, for example `Resources.Rooms.records.studio_a.name`. A page that reads a value sends it to every viewer. A static resource has no capabilities. It can have a `belongs_to` or `belongs_to_many` relation only to another static resource, because the relation is stored on its records. A record sets that relation with the `uid` of a target record, or a list of uids for `belongs_to_many`, and the build checks each uid. The deploy writes the target records first, so the build refuses a cycle of these relations, and a relation of a static resource to itself.
785
809
 
786
810
  There is one `field.<type>` builder for each resource field type, in camel case: `field.eventSchedule()` stores an `event_schedule` field. `field.file()` stores a `file_reference` field, and there is no `field.fileReference()`. `field.longText()` stores a `text` field, the same type as `field.text()`. `fields.generated.d.ts` declares the builders, `fields.generated.js` implements them, and `field-catalog.json` lists their settings. `npm run generate-types` generates the three files from the platform field types. Do not edit them.
787
811
 
788
- A builder takes these options:
812
+ A field file holds one builder call, `export default field.<type>({...})`. The file name is the field key, so a file rename is a key rename. A builder takes these options:
789
813
 
790
814
  - `uid`: the stable identity of the field, unique in its resource. `diagonal check` writes a missing one. See [Definition uids and slugs](#definition-uids-and-slugs). The deploy stores it on the field, but the stored field id still derives from the resource and the field key, so a renamed key is still a new field.
791
815
  - `label`, `description`, `required`, `default`, `unique`, and `index`.
@@ -795,25 +819,36 @@ A builder takes these options:
795
819
  - `getter`: a resolver tree that transforms the stored value when it is read.
796
820
  - `setter`: a resolver tree that computes the stored value before each create and update. `setterWhenEmpty: true` runs it only when the value is null or empty.
797
821
 
798
- `field.select` takes `options` and `field.relation` takes `resource` (`Resources.<Name>.slug`) and `type` as options. Other settings go in `settings`. A setting that an option writes, such as `settings.unique`, is refused. A relation can declare `settings.inverse: { uid, key, label?, settings? }`. `uid` is the uid of the inverse field. The build then adds the inverse relation field to the target resource. A target that declares a field with the same key is an error.
822
+ `field.select` takes `options` and `field.relation` takes `resource` (`Resources.<Name>.slug`) and `type` as options. A relation file imports `Resources` from `@app/generated/resources`. Other settings go in `settings`. A setting that an option writes, such as `settings.unique`, is refused. A relation can declare `settings.inverse: { uid, key, label?, settings? }` in its own field file. `uid` is the uid of the inverse field. The build then adds the inverse relation field to the target resource, which has no file for it. A target that declares a field with the same key is an error.
823
+
824
+ ```ts
825
+ // resources/classes/fields/instructor.ts
826
+ import { Resources } from '@app/generated/resources';
827
+ import { field } from '@diagonal-hq/cli';
828
+
829
+ export default field.relation({
830
+ uid: '01a1d9ed-c224-7473-8812-9c54905a654b',
831
+ label: 'Instructor',
832
+ resource: Resources.Instructors.slug,
833
+ type: 'belongs_to',
834
+ settings: {
835
+ inverse: { uid: '7f7f697e-f620-4cc6-bfab-522421d501d7', key: 'classes', label: 'Classes' }
836
+ }
837
+ });
838
+ ```
799
839
 
800
840
  The platform deploy validates every field again with the rules of the resource builder, so a value that the build cannot check, such as an unknown guard rule, fails the deploy with the file path.
801
841
 
802
842
  ## Capabilities
803
843
 
804
- A resource gets a platform capability, such as Authenticatable, Notifiable, Payable, Subscription, or Eventable, from its `capabilities` key. The settings have the names that the resource builder uses. A field reference names a field of the same resource by its key:
844
+ A resource gets a platform capability, such as Authenticatable, Notifiable, Payable, Subscription, or Eventable, from the `capabilities` key of its `resource.ts`. The settings have the names that the resource builder uses. A field reference names a field of the same resource by its key:
805
845
 
806
846
  ```ts
807
- export default defineResource({
847
+ // resources/members/resource.ts, with fields/name.ts, fields/email.ts, and fields/password.ts
848
+ export default defineResource<'members'>({
808
849
  uid: '0199f300-0000-7000-8000-000000000005',
809
850
  name: 'Members',
810
851
  singularName: 'Member',
811
- fields: {
812
- name: field.text({ required: true }),
813
- email: field.email({ required: true, unique: true }),
814
- password: field.password()
815
- },
816
- policies: [],
817
852
  capabilities: {
818
853
  authenticatable: { email_field: 'email', password_field: 'password' },
819
854
  notifiable: { email_field: 'email' }
@@ -823,7 +858,7 @@ export default defineResource({
823
858
 
824
859
  `capabilities.generated.d.ts` declares the settings of each capability, and `capability-catalog.json` lists them. `npm run generate-types` generates both from the platform capabilities. Do not edit them.
825
860
 
826
- - The types accept only a field key whose field type the setting allows. For example, `notifiable.email_field` accepts only an `email` field.
861
+ - The build accepts only a field key whose field type the setting allows. For example, `notifiable.email_field` accepts only an `email` field. With the folder type argument, such as `defineResource<'members'>({...})`, the editor checks the key after the build generates the types of the folder. Without the argument, the editor accepts any key.
827
862
  - A file cannot declare `role` or `permission`. Authorization provisioning owns the Role and Permission resources. It also maps `authenticatable.roles_field`, so a file cannot set it.
828
863
  - A page reference setting names a page file by its uid, as `Pages.<Name>.uid` from `@app/generated/pages`. These settings are `authenticatable.login_page`, `authenticatable.login_redirect`, and `schedulable.calendar_connections_page`. See [Page reference settings](#page-reference-settings).
829
864
  - The build checks the setting names, the required settings, the select values, and each field reference. A relation path, such as an Itemizable offering path, names a relation of each resource on the way.
@@ -832,24 +867,20 @@ export default defineResource({
832
867
  - After the deploy, the platform runs the same provisioning as the resource builder. It creates the system fields of a Subscription, the accounting entity fields, the billing relations, the record indexes, and the booking and schedule setup. For an Authenticatable resource, it creates the Role and Permission resources, so members can sign in.
833
868
  - A setting that provisioning fills can be left out. A Subscription starts from the builder's default settings, so set only the defaults that change.
834
869
  - Provisioning can create a field, for example `accounting_entity`. The files cannot declare a field with the same key later. Use another key.
835
- - The resource builder and the API refuse a capability change in a file-based workspace. Change the resource file, then commit it. The commit deploys.
870
+ - The resource builder and the API refuse a capability change in a file-based workspace. Change `resource.ts`, then commit it. The commit deploys.
836
871
 
837
872
  ### Page reference settings
838
873
 
839
874
  A capability setting that names a page takes the uid of a page file. Import `Pages` from `@app/generated/pages` and use `Pages.<Name>.uid`:
840
875
 
841
876
  ```ts
877
+ // resources/members/resource.ts
842
878
  import { Pages } from '@app/generated/pages';
843
- import { defineResource, field } from '@diagonal-hq/cli';
879
+ import { defineResource } from '@diagonal-hq/cli';
844
880
 
845
- export default defineResource({
881
+ export default defineResource<'members'>({
846
882
  name: 'Members',
847
883
  singularName: 'Member',
848
- fields: {
849
- email: field.email({ required: true, unique: true }),
850
- password: field.password()
851
- },
852
- policies: [],
853
884
  capabilities: {
854
885
  authenticatable: {
855
886
  email_field: 'email',
@@ -862,9 +893,9 @@ export default defineResource({
862
893
  });
863
894
  ```
864
895
 
865
- The build writes `generated/pages.ts` from the page files, before it builds the resource files. Each property is the page name: the studly case of each folder and file name below `pages/`, joined with `_`, without `.tsx`. A route parameter segment such as `[id]` gets the prefix `$`. `pages/sign-in.tsx` is `SignIn`, `pages/members/[id].tsx` is `Members_$Id`, `pages/classes/index.tsx` is `Classes_Index`, and `pages/404.tsx` is `Page404`. Its value holds the `uid` and the `route` of the page. Two files with one name fail at the second file. `diagonal check` writes a missing page uid before it builds the resource files, so a new page can be named in the same run.
896
+ The build writes `generated/pages.ts` from the page files, before it builds the resources. Each property is the page name: the studly case of each folder and file name below `pages/`, joined with `_`, without `.tsx`. A route parameter segment such as `[id]` gets the prefix `$`. `pages/sign-in.tsx` is `SignIn`, `pages/members/[id].tsx` is `Members_$Id`, `pages/classes/index.tsx` is `Classes_Index`, and `pages/404.tsx` is `Page404`. Its value holds the `uid` and the `route` of the page. Two files with one name fail at the second file. `diagonal check` writes a missing page uid before it builds the resources, so a new page can be named in the same run.
866
897
 
867
- - The build reads `Pages.<Name>.uid` like a literal. In a config or resource file, an unknown name, and any other property, such as `Pages.Index.route`, is an error at its location.
898
+ - The build reads `Pages.<Name>.uid` like a literal. In a config file or a `resource.ts`, an unknown name, and any other property, such as `Pages.Index.route`, is an error at its location.
868
899
  - The page route must not have a parameter, because the platform links the page without route values. A page with a route parameter, such as `/members/{id}`, is an error at the setting.
869
900
  - The deploy stores the setting as `{ id }` with the page uid, which is the page id. A file move or rename changes the page name in code, and `diagonal check` reports each stale `Pages.<Name>`. The uid stays, so the stored setting still resolves.
870
901
  - The login form, the login redirect, and the calendar email links use the page only when the active deployment serves it and the page is not paused. Otherwise they fall back, as they do for a page row.
@@ -874,46 +905,45 @@ The build writes `generated/pages.ts` from the page files, before it builds the
874
905
 
875
906
  ## Policies
876
907
 
877
- A policy grants access to the records of its resource. Each policy option maps to one option of a stored policy:
908
+ A policy grants access to the records of its resource. Each policy is a file `policies/<key>.ts` in the folder of its resource, with `export default definePolicy({...})`. Each policy option maps to one option of a stored policy. These two files give the policies of a Posts resource whose folder has the fields `title`, `body`, and `author`:
878
909
 
879
910
  ```ts
911
+ // resources/posts/policies/visitors_read_titles.ts
912
+ import { definePolicy } from '@diagonal-hq/cli';
913
+
914
+ export default definePolicy<'posts'>({
915
+ name: 'Visitors read titles',
916
+ scope: ['index', 'show'],
917
+ access: 'public',
918
+ fields: ['id', 'title']
919
+ });
920
+ ```
921
+
922
+ ```ts
923
+ // resources/posts/policies/authors_edit_their_posts.ts
880
924
  import { Resources } from '@app/generated/resources';
925
+ import { definePolicy } from '@diagonal-hq/cli';
881
926
 
882
- export default defineResource({
883
- name: 'Posts',
884
- singularName: 'Post',
885
- fields: {
886
- title: field.text({ required: true }),
887
- body: field.text(),
888
- author: field.relation({ resource: Resources.Members.slug, type: 'belongs_to' })
927
+ export default definePolicy<'posts'>({
928
+ name: 'Authors edit their posts',
929
+ scope: ['update', 'destroy'],
930
+ resource: Resources.Members.slug,
931
+ filter: {
932
+ operator: 'and',
933
+ conditions: [
934
+ {
935
+ field: 'author.id',
936
+ operator: '=',
937
+ value: { $type: 'user.current', $value: { key: 'id' } }
938
+ }
939
+ ]
889
940
  },
890
- policies: [
891
- {
892
- name: 'Visitors read titles',
893
- scope: ['index', 'show'],
894
- access: 'public',
895
- fields: ['id', 'title']
896
- },
897
- {
898
- name: 'Authors edit their posts',
899
- scope: ['update', 'destroy'],
900
- resource: Resources.Members.slug,
901
- filter: {
902
- operator: 'and',
903
- conditions: [
904
- {
905
- field: 'author.id',
906
- operator: '=',
907
- value: { $type: 'user.current', $value: { key: 'id' } }
908
- }
909
- ]
910
- },
911
- fields: ['title', 'body']
912
- }
913
- ]
941
+ fields: ['title', 'body']
914
942
  });
915
943
  ```
916
944
 
945
+ The studly case of the file name is the key of the policy in `Resources.<Name>.policies`, so `visitors_read_titles.ts` is `Resources.Posts.policies.VisitorsReadTitles`. Two file names with one studly key give a warning. The policies build in the order of their paths. A policy save in the app writes the file of each new or changed policy and deletes the file of each removed policy. It leaves each other policy file as written. A new policy file gets the snake case of the policy name, with `_2` and so on when the folder already has that file name.
946
+
917
947
  - `uid` is the stable identity of the policy, unique in its resource. `diagonal check` writes a missing one. See [Definition uids and slugs](#definition-uids-and-slugs).
918
948
  - `name` is the display label of the policy. Two policies can have one name.
919
949
  - `scope` is `'all'` or a list of operations: `index`, `show`, `count`, `aggregate`, `store`, `store_many`, `update`, `destroy`, `restore`, and `validate`. A scope is snake case, as a `dataApi.endpoints` name such as `create_many` is.