@pplethai/cli 0.9.0 → 0.11.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 (38) hide show
  1. package/dist/bin.js +128 -125
  2. package/package.json +1 -1
  3. package/templates/golden-path/.dev.vars.example +4 -3
  4. package/templates/golden-path/CLAUDE.md +13 -6
  5. package/templates/golden-path/README.md +5 -4
  6. package/templates/golden-path/src/call-service.ts +17 -10
  7. package/templates/golden-path/src/dev-call-service.ts +21 -20
  8. package/templates/golden-path/src/dev-read-dataset.ts +55 -40
  9. package/templates/golden-path/src/dev-registry.ts +25 -7
  10. package/templates/golden-path/src/entry-name.ts +114 -0
  11. package/templates/golden-path/src/env.ts +2 -2
  12. package/templates/golden-path/src/read-dataset.ts +130 -16
  13. package/templates/golden-path/src/registry.ts +1 -1
  14. package/templates/golden-path/test/call-service.test.ts +118 -8
  15. package/templates/golden-path/test/dev-call-service.test.ts +201 -25
  16. package/templates/golden-path/test/dev-read-dataset.test.ts +122 -13
  17. package/templates/golden-path/test/dev-registry.test.ts +35 -6
  18. package/templates/golden-path/test/fixtures/overlay/catalog/entry.md +8 -0
  19. package/templates/golden-path/test/fixtures/overlay/election/2027/score/entry.md +11 -0
  20. package/templates/golden-path/test/fixtures/overlay/election/2027/score/mocks/responses.json +7 -0
  21. package/templates/golden-path/test/fixtures/overlay/election/results/entry.md +24 -0
  22. package/templates/golden-path/test/fixtures/overlay/election/results/mocks/turnout.json +1 -0
  23. package/templates/golden-path/test/fixtures/overlay/platform/sms/entry.md +10 -0
  24. package/templates/golden-path/test/fixtures/overlay/platform/sms/mocks/responses.json +7 -0
  25. package/templates/golden-path/test/fixtures/overlay/score/entry.md +10 -0
  26. package/templates/golden-path/test/fixtures/overlay/score/mocks/responses.json +7 -0
  27. package/templates/golden-path/test/harness.ts +1 -1
  28. package/templates/golden-path/test/read-dataset.test.ts +187 -14
  29. package/templates/golden-path/test/fixtures/overlay/shop/catalog/entry.md +0 -8
  30. /package/templates/golden-path/test/fixtures/overlay/{directory/branches → branch-list}/entry.md +0 -0
  31. /package/templates/golden-path/test/fixtures/overlay/{directory/branches → branch-list}/mocks/audience.json +0 -0
  32. /package/templates/golden-path/test/fixtures/overlay/{directory/branches → branch-list}/mocks/named.json +0 -0
  33. /package/templates/golden-path/test/fixtures/overlay/{directory/branches → branch-list}/mocks/offices.json +0 -0
  34. /package/templates/golden-path/test/fixtures/overlay/{directory/branches → branch-list}/mocks/roster.json +0 -0
  35. /package/templates/golden-path/test/fixtures/overlay/{directory/branches → branch-list}/mocks/summary.json +0 -0
  36. /package/templates/golden-path/test/fixtures/overlay/{shop/catalog → catalog}/mocks/responses.json +0 -0
  37. /package/templates/golden-path/test/fixtures/overlay/{shop/orders → orders}/entry.md +0 -0
  38. /package/templates/golden-path/test/fixtures/overlay/{shop/orders → orders}/mocks/responses.json +0 -0
@@ -0,0 +1,114 @@
1
+ // A Registry Entry is named by its full name: one bare segment (`branch-list`),
2
+ // or a Namespace (กลุ่มชื่อ) plus one to three more segments (`election/score`,
3
+ // `election/2027/score`). The Provider is not part of the name (ADR-0031,
4
+ // ADR-0032). The platform's own entries all sit under the Namespace `platform`:
5
+ // `platform/sms`, `platform/legal-identity`.
6
+ //
7
+ // A copy of the name rules in workers/src/shared/registry/validate.ts. This
8
+ // file is copied into a Builder App, which cannot import the platform
9
+ // package. cli/test/registry-entry-name.test.ts keeps the two in step.
10
+ //
11
+ // `platform` is reserved for apps: no app may use it as a bare name or a
12
+ // Namespace. That is why `platform/<x>` is the platform's name and never an
13
+ // app's. A Consumer calls it by that name, so it passes here; the bare
14
+ // `platform` does not.
15
+
16
+ /** The slug shape of one segment: lowercase words joined by single hyphens. */
17
+ const SEGMENT = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
18
+ /** The longest one segment may be. */
19
+ const SEGMENT_MAX = 63;
20
+ /** The longest a full name may be, slashes included. */
21
+ export const ENTRY_FULL_NAME_MAX = 128;
22
+ /** A Namespace plus at most three path segments. */
23
+ export const ENTRY_NAME_MAX_SEGMENTS = 4;
24
+ /** The Namespace of every platform entry (`platform/sms`). The platform holds it; no app may. */
25
+ export const PLATFORM_NAMESPACE = "platform";
26
+ /** Names the platform keeps for itself. Rejected as a bare name and as an app's Namespace. */
27
+ export const RESERVED_ENTRY_NAMES: ReadonlySet<string> = new Set(["health", "overlay", "platform"]);
28
+
29
+ /**
30
+ * Why `name` is not an entry name, or null when it is one. Reserved first
31
+ * segments are reported apart from other shape problems so a caller can say
32
+ * more about them. `platform/<path>` is an entry name: the platform's own
33
+ * Namespace, which only the platform publish holds. The bare `platform` is not.
34
+ */
35
+ export function entryNameProblem(name: string): "shape" | "reserved" | null {
36
+ if (name.length > ENTRY_FULL_NAME_MAX) return "shape";
37
+ const segments = name.split("/");
38
+ if (segments.length > ENTRY_NAME_MAX_SEGMENTS) return "shape";
39
+ if (!segments.every((segment) => segment.length <= SEGMENT_MAX && SEGMENT.test(segment))) return "shape";
40
+ const top = segments[0] ?? "";
41
+ if (top === PLATFORM_NAMESPACE && segments.length > 1) return null;
42
+ return RESERVED_ENTRY_NAMES.has(top) ? "reserved" : null;
43
+ }
44
+
45
+ /** True when `name` is one an entry may have. */
46
+ export function isEntryName(name: string): boolean {
47
+ return entryNameProblem(name) === null;
48
+ }
49
+
50
+ /** Why `name` is refused, in a sentence. Null when it is fine. */
51
+ export function entryNameError(name: string): string | null {
52
+ const problem = entryNameProblem(name);
53
+ if (problem === null) return null;
54
+ if (problem === "reserved") {
55
+ const top = name.split("/")[0] ?? name;
56
+ if (top === PLATFORM_NAMESPACE) {
57
+ return `"${name}" is not an entry name: "platform" belongs to the platform, and its entries are named under it, such as "platform/sms"`;
58
+ }
59
+ return `"${top}" is reserved by the platform and cannot start an entry name`;
60
+ }
61
+ return (
62
+ `"${name}" is not an entry name: use one bare name such as "branch-list", or a Namespace and up to ` +
63
+ `${ENTRY_NAME_MAX_SEGMENTS - 1} more names such as "election/2027/score" ` +
64
+ `(lowercase letters, digits and hyphens; at most ${ENTRY_FULL_NAME_MAX} characters)`
65
+ );
66
+ }
67
+
68
+ /**
69
+ * Throws unless `entry` is an entry name. `fn` is the public function that
70
+ * received it, so the message names the call the Builder wrote.
71
+ */
72
+ export function assertEntryName(fn: string, entry: string): void {
73
+ const error = entryNameError(entry);
74
+ if (error) throw new Error(`${fn} entry ${error}`);
75
+ }
76
+
77
+ /** Where the workspace overlay lives. The CLI writes one folder per entry under it. */
78
+ export const OVERLAY_ROOT = ".pple/registry/";
79
+
80
+ /**
81
+ * `file` (a glob key or a path) relative to the overlay root, posix, or null
82
+ * when it is not under `root`. The root must start at a path boundary, so
83
+ * `x.pple/registry/` is not a root. Tests pass their own `root` for a fixture
84
+ * folder, because CI has no `.pple/`.
85
+ */
86
+ export function overlayRelative(file: string, root: string = OVERLAY_ROOT): string | null {
87
+ const path = file.split("?")[0]?.replaceAll("\\", "/") ?? file;
88
+ let from = 0;
89
+ for (;;) {
90
+ const at = path.indexOf(root, from);
91
+ if (at === -1) return null;
92
+ if (at === 0 || path[at - 1] === "/") return path.slice(at + root.length);
93
+ from = at + 1;
94
+ }
95
+ }
96
+
97
+ /**
98
+ * The entry full name a file under the overlay belongs to, with the file's
99
+ * place inside that entry's folder (`entry.md`, `mocks/orders.json`). An entry
100
+ * folder is nested for a namespaced entry, so the name is every folder above
101
+ * `entry.md` or `mocks/`. Null for a file that is neither.
102
+ */
103
+ export function overlayEntryFile(
104
+ file: string,
105
+ root: string = OVERLAY_ROOT,
106
+ ): { name: string; inside: string } | null {
107
+ const relative = overlayRelative(file, root);
108
+ if (relative === null) return null;
109
+ const entryMd = /^(.+)\/(entry\.md)$/.exec(relative);
110
+ if (entryMd?.[1] && entryMd[2]) return { name: entryMd[1], inside: entryMd[2] };
111
+ const mock = /^(.+)\/(mocks\/[^/]+\.json)$/.exec(relative);
112
+ if (mock?.[1] && mock[2]) return { name: mock[1], inside: mock[2] };
113
+ return null;
114
+ }
@@ -27,8 +27,8 @@ export interface Env {
27
27
 
28
28
  // Local development only: make offline `callService` and `readDataset`
29
29
  // return a platform refusal instead of a mock (`not_granted`,
30
- // `level_not_met`, …). A bare code applies to every entry;
31
- // `<provider>/<name>=<code>` wins for that entry. Comma-separated.
30
+ // `level_not_met`, `renamed`, …). A bare code applies to every entry;
31
+ // `<name>=<code>` wins for that entry. Comma-separated.
32
32
  // Compiled out with the offline path.
33
33
  DEV_REGISTRY_ERROR?: string;
34
34
 
@@ -12,6 +12,7 @@
12
12
 
13
13
  import { callService, PLATFORM_ERROR_HEADER, type CallServiceEnv } from "./call-service";
14
14
  import { answerOfflineRead } from "./dev-read-dataset";
15
+ import { assertEntryName } from "./entry-name";
15
16
 
16
17
  /** One page of a collection. `next` is null on the last page. */
17
18
  export interface DatasetPage<T = Record<string, unknown>> {
@@ -56,6 +57,7 @@ interface ReadDatasetCommon {
56
57
  export interface ReadDatasetPageOptions extends ReadDatasetCommon {
57
58
  shape?: "collection";
58
59
  id?: undefined;
60
+ ifNoneMatch?: undefined;
59
61
  /** Equality, a repeated value (`in`), or `{ gt, gte, lt, lte }`. */
60
62
  filter?: Record<string, DatasetFilterValue>;
61
63
  /** `<index>` or `-<index>`. Omitted sorts by id ascending. */
@@ -75,6 +77,7 @@ export interface ReadDatasetPageOptions extends ReadDatasetCommon {
75
77
  export interface ReadDatasetSingletonOptions extends ReadDatasetCommon {
76
78
  shape: "singleton";
77
79
  id?: undefined;
80
+ ifNoneMatch?: undefined;
78
81
  /** Sent as-is. The platform answers `invalid_query` for any query on a singleton. */
79
82
  filter?: Record<string, DatasetFilterValue>;
80
83
  sort?: string;
@@ -86,17 +89,68 @@ export interface ReadDatasetLookupOptions extends ReadDatasetCommon {
86
89
  /** Look up this id. A query string as well is `invalid_query`. */
87
90
  id: string;
88
91
  shape?: "collection" | "singleton";
92
+ ifNoneMatch?: undefined;
89
93
  filter?: Record<string, DatasetFilterValue>;
90
94
  sort?: string;
91
95
  limit?: number;
92
96
  next?: string;
93
97
  }
94
98
 
99
+ /**
100
+ * The conditional forms: the same three single-request shapes, plus an
101
+ * `ifNoneMatch` that is sent as `If-None-Match`. Passing one widens the result
102
+ * to include `DatasetNotModified`. `follow: true` is not accepted with it:
103
+ * a walk has one ETag per page, so one conditional request does not apply. It
104
+ * is a type error, and `readDataset` throws if it gets one anyway.
105
+ */
106
+ interface Conditional {
107
+ /**
108
+ * An `etag` from an earlier success or not-modified result. Sent as
109
+ * `If-None-Match`. When the data has not changed the platform answers `304`
110
+ * and `readDataset` returns `{ ok: true, status: 304, etag, notModified: true }`
111
+ * with no `data`. Otherwise the answer is the usual success or refusal.
112
+ * `undefined` (a first read, with nothing cached yet) sends no header.
113
+ */
114
+ ifNoneMatch: string | undefined;
115
+ }
116
+
117
+ export type ReadDatasetConditionalPageOptions = Omit<ReadDatasetPageOptions, "ifNoneMatch" | "follow"> &
118
+ Conditional & { follow?: false };
119
+ export type ReadDatasetConditionalSingletonOptions = Omit<ReadDatasetSingletonOptions, "ifNoneMatch"> &
120
+ Conditional;
121
+ export type ReadDatasetConditionalLookupOptions = Omit<ReadDatasetLookupOptions, "ifNoneMatch"> & Conditional;
122
+
123
+ type AnyReadOptions =
124
+ | ReadDatasetPageOptions
125
+ | ReadDatasetSingletonOptions
126
+ | ReadDatasetLookupOptions
127
+ | ReadDatasetConditionalPageOptions
128
+ | ReadDatasetConditionalSingletonOptions
129
+ | ReadDatasetConditionalLookupOptions;
130
+
95
131
  export type DatasetSuccess<T> = {
96
132
  ok: true;
97
133
  status: number;
98
134
  etag: string | null;
99
135
  data: T;
136
+ notModified?: undefined;
137
+ };
138
+
139
+ /**
140
+ * The answer to a conditional read (`ifNoneMatch`) when the platform said
141
+ * `304`: what the Builder already holds is still current. There is no `data`.
142
+ * `etag` is the platform's `ETag`, the same value that was sent.
143
+ *
144
+ * It only comes back from a read that passed `ifNoneMatch`. Narrow it with
145
+ * `result.ok && result.notModified`: on `true` the result is this type, and
146
+ * after `if (result.ok && !result.notModified)` it is a `DatasetSuccess` with
147
+ * `data`. A refusal has `ok: false`, so it never has `notModified`.
148
+ */
149
+ export type DatasetNotModified = {
150
+ ok: true;
151
+ status: 304;
152
+ etag: string | null;
153
+ notModified: true;
100
154
  };
101
155
 
102
156
  /**
@@ -113,16 +167,48 @@ export type DatasetFailure = {
113
167
 
114
168
  export type DatasetResult<T> = DatasetSuccess<T> | DatasetFailure;
115
169
 
170
+ /** What a conditional read returns: a `DatasetResult`, or `DatasetNotModified`. */
171
+ export type DatasetConditionalResult<T> = DatasetResult<T> | DatasetNotModified;
172
+
116
173
  const RANGE_OPS = ["gt", "gte", "lt", "lte"] as const;
117
174
  const FOLLOW_ATTEMPTS = 3;
118
175
 
119
176
  /**
120
- * `GET services.<domain>/<provider>/<name>/<objectType>[/<id>]`.
177
+ * `GET services.<domain>/<full name>/<objectType>[/<id>]`. `entry` is the full
178
+ * name: a bare name such as `"branch-list"`, a Namespace and a path such as
179
+ * `"election/score"`, or a platform entry such as `"platform/<name>"`. A name
180
+ * the shared validator refuses throws, the bare `"platform"` included.
121
181
  *
122
182
  * A collection (the default) is a page. `shape: "singleton"` or `id` is one
123
183
  * object. `follow: true` walks a collection to the end. The App Key is always
124
184
  * `Authorization: Bearer`.
185
+ *
186
+ * Polling: pass `ifNoneMatch: <the last etag>` on a page, a singleton or an id
187
+ * lookup. It is sent as `If-None-Match`. A `304` comes back as
188
+ * `{ ok: true, status: 304, etag, notModified: true }` with no `data`
189
+ * (`DatasetNotModified`), so keep what you read last time. A `200` with a
190
+ * different ETag is the usual success, with the new `etag`. `ifNoneMatch` with
191
+ * `follow: true` is refused: it is a type error, and `readDataset` throws.
192
+ * Offline answers the same way, from the mock's content.
125
193
  */
194
+ export async function readDataset<T extends Record<string, unknown> = Record<string, unknown>>(
195
+ env: CallServiceEnv,
196
+ entry: string,
197
+ objectType: string,
198
+ options: ReadDatasetConditionalLookupOptions,
199
+ ): Promise<DatasetConditionalResult<DatasetObject<T>>>;
200
+ export async function readDataset<T extends Record<string, unknown> = Record<string, unknown>>(
201
+ env: CallServiceEnv,
202
+ entry: string,
203
+ objectType: string,
204
+ options: ReadDatasetConditionalSingletonOptions,
205
+ ): Promise<DatasetConditionalResult<DatasetObject<T>>>;
206
+ export async function readDataset<T extends Record<string, unknown> = Record<string, unknown>>(
207
+ env: CallServiceEnv,
208
+ entry: string,
209
+ objectType: string,
210
+ options: ReadDatasetConditionalPageOptions,
211
+ ): Promise<DatasetConditionalResult<DatasetPage<T>>>;
126
212
  export async function readDataset<T extends Record<string, unknown> = Record<string, unknown>>(
127
213
  env: CallServiceEnv,
128
214
  entry: string,
@@ -145,11 +231,9 @@ export async function readDataset<T extends Record<string, unknown> = Record<str
145
231
  env: CallServiceEnv,
146
232
  entry: string,
147
233
  objectType: string,
148
- options: ReadDatasetPageOptions | ReadDatasetSingletonOptions | ReadDatasetLookupOptions = {},
149
- ): Promise<DatasetResult<DatasetPage<T> | DatasetObject<T>>> {
150
- if (!/^[^/\s]+\/[^/\s]+$/.test(entry)) {
151
- throw new Error('readDataset entry must be "<provider>/<name>"');
152
- }
234
+ options: AnyReadOptions = {},
235
+ ): Promise<DatasetConditionalResult<DatasetPage<T> | DatasetObject<T>>> {
236
+ assertEntryName("readDataset", entry);
153
237
  if (objectType === "" || /[/\s?#]/.test(objectType)) {
154
238
  throw new Error("readDataset objectType must be one path segment");
155
239
  }
@@ -157,6 +241,10 @@ export async function readDataset<T extends Record<string, unknown> = Record<str
157
241
  throw new Error("readDataset id must not be empty");
158
242
  }
159
243
 
244
+ // The types refuse this pair. A caller that got past them (JS, a cast) throws.
245
+ if (options.ifNoneMatch !== undefined && (options as { follow?: boolean }).follow === true) {
246
+ throw new Error("readDataset ifNoneMatch does not apply with follow: a walk has one ETag per page");
247
+ }
160
248
  if (isPageRequest(options) && options.follow === true) {
161
249
  return followPages(env, entry, objectType, options);
162
250
  }
@@ -186,7 +274,7 @@ async function walkPages<T extends Record<string, unknown>>(
186
274
  options: ReadDatasetPageOptions,
187
275
  cursor: string | undefined,
188
276
  ): Promise<{ outcome: "done"; result: DatasetResult<DatasetPage<T>> } | { outcome: "moved" }> {
189
- const first = await readOnce<T>(env, entry, objectType, pageOptions(options, cursor));
277
+ const first = await readPage<T>(env, entry, objectType, pageOptions(options, cursor));
190
278
  if (!first.ok) return { outcome: "done", result: first };
191
279
  if (!isPage<T>(first.data)) return { outcome: "done", result: { ok: false, status: first.status, error: null } };
192
280
 
@@ -200,7 +288,7 @@ async function walkPages<T extends Record<string, unknown>>(
200
288
  while (next !== null) {
201
289
  if (seen.has(next)) return { outcome: "done", result: { ok: false, status: 400, error: null } };
202
290
  seen.add(next);
203
- const page = await readOnce<T>(env, entry, objectType, pageOptions(options, next));
291
+ const page = await readPage<T>(env, entry, objectType, pageOptions(options, next));
204
292
  if (!page.ok) return { outcome: "done", result: page };
205
293
  if (!isPage<T>(page.data)) return { outcome: "done", result: { ok: false, status: page.status, error: null } };
206
294
  if (page.data.snapshot !== snapshot) return { outcome: "moved" };
@@ -225,19 +313,36 @@ function pageOptions(options: ReadDatasetPageOptions, next: string | undefined):
225
313
  return { ...rest, next };
226
314
  }
227
315
 
228
- async function readOnce<T extends Record<string, unknown>>(
316
+ /** One page of a walk. A walk never sends `ifNoneMatch`, so it is never `304`. */
317
+ async function readPage<T extends Record<string, unknown>>(
229
318
  env: CallServiceEnv,
230
319
  entry: string,
231
320
  objectType: string,
232
- options: ReadDatasetPageOptions | ReadDatasetSingletonOptions | ReadDatasetLookupOptions,
321
+ options: ReadDatasetPageOptions,
233
322
  ): Promise<DatasetResult<DatasetPage<T> | DatasetObject<T>>> {
323
+ const result = await readOnce<T>(env, entry, objectType, options);
324
+ if (result.ok && result.notModified) return { ok: false, status: result.status, error: null };
325
+ return result;
326
+ }
327
+
328
+ async function readOnce<T extends Record<string, unknown>>(
329
+ env: CallServiceEnv,
330
+ entry: string,
331
+ objectType: string,
332
+ options: AnyReadOptions,
333
+ ): Promise<DatasetConditionalResult<DatasetPage<T> | DatasetObject<T>>> {
234
334
  const response = await load(env, entry, objectType, options);
235
335
  const error = response.headers.get(PLATFORM_ERROR_HEADER);
236
336
  if (error !== null) return { ok: false, status: response.status, error };
337
+ const etag = response.headers.get("etag");
338
+ // Only a conditional read can be answered 304. Without `ifNoneMatch` a 304
339
+ // is not something the platform sends, and stays a failure below.
340
+ if (response.status === 304 && sentIfNoneMatch(options)) {
341
+ return { ok: true, status: 304, etag, notModified: true };
342
+ }
237
343
  if (!response.ok) return { ok: false, status: response.status, error: null };
238
344
 
239
345
  const body = (await response.json().catch(() => null)) as unknown;
240
- const etag = response.headers.get("etag");
241
346
  if (isObjectRequest(options)) {
242
347
  const data = asObject<T>(body);
243
348
  if (!data) return { ok: false, status: response.status, error: null };
@@ -252,9 +357,10 @@ function load(
252
357
  env: CallServiceEnv,
253
358
  entry: string,
254
359
  objectType: string,
255
- options: ReadDatasetPageOptions | ReadDatasetSingletonOptions | ReadDatasetLookupOptions,
360
+ options: AnyReadOptions,
256
361
  ): Promise<Response> {
257
362
  const search = datasetSearch(options);
363
+ const ifNoneMatch = sentIfNoneMatch(options) ? options.ifNoneMatch : undefined;
258
364
  // `import.meta.env.DEV` is false in the production build, so this branch
259
365
  // and `dev-read-dataset.ts` are absent from the deployed Worker. Vitest
260
366
  // keeps the injected fetch even when a Persona is set.
@@ -263,10 +369,13 @@ function load(
263
369
  id: "id" in options ? options.id : undefined,
264
370
  search,
265
371
  userToken: options.userToken,
372
+ ifNoneMatch,
266
373
  }));
267
374
  }
268
375
  const id = "id" in options ? options.id : undefined;
269
- return callService(env, entry, datasetPath(objectType, id, search), { method: "GET" }, {
376
+ const init: RequestInit = { method: "GET" };
377
+ if (ifNoneMatch !== undefined) init.headers = { "if-none-match": ifNoneMatch };
378
+ return callService(env, entry, datasetPath(objectType, id, search), init, {
270
379
  userToken: options.userToken,
271
380
  fetchImpl: options.fetchImpl,
272
381
  });
@@ -287,7 +396,7 @@ function datasetPath(
287
396
  }
288
397
 
289
398
  function datasetSearch(
290
- options: ReadDatasetPageOptions | ReadDatasetSingletonOptions | ReadDatasetLookupOptions,
399
+ options: AnyReadOptions,
291
400
  ): [string, string][] {
292
401
  const entries: [string, string][] = [];
293
402
  const filter = "filter" in options ? options.filter : undefined;
@@ -313,6 +422,11 @@ function datasetSearch(
313
422
  return entries;
314
423
  }
315
424
 
425
+ /** True when the caller gave a non-empty `ifNoneMatch`. An empty string sends no header. */
426
+ function sentIfNoneMatch(options: AnyReadOptions): options is AnyReadOptions & { ifNoneMatch: string } {
427
+ return typeof options.ifNoneMatch === "string" && options.ifNoneMatch !== "";
428
+ }
429
+
316
430
  function isRange(value: DatasetFilterValue): value is DatasetRange {
317
431
  if (typeof value !== "object") return false;
318
432
  const keys = Object.keys(value);
@@ -320,13 +434,13 @@ function isRange(value: DatasetFilterValue): value is DatasetRange {
320
434
  }
321
435
 
322
436
  function isPageRequest(
323
- options: ReadDatasetPageOptions | ReadDatasetSingletonOptions | ReadDatasetLookupOptions,
437
+ options: AnyReadOptions,
324
438
  ): options is ReadDatasetPageOptions {
325
439
  return !("id" in options && options.id !== undefined) && options.shape !== "singleton";
326
440
  }
327
441
 
328
442
  function isObjectRequest(
329
- options: ReadDatasetPageOptions | ReadDatasetSingletonOptions | ReadDatasetLookupOptions,
443
+ options: AnyReadOptions,
330
444
  ): boolean {
331
445
  return ("id" in options && options.id !== undefined) || options.shape === "singleton";
332
446
  }
@@ -22,7 +22,7 @@ export const IDENTITY_HEADER = "x-pple-identity";
22
22
  export interface ServiceCall {
23
23
  /** The Consumer, named from its App Key. */
24
24
  consumer: string;
25
- /** `<provider>/<name>`. */
25
+ /** The entry's full name (`sms`, `election/2027/score`), from `x-pple-entry`. */
26
26
  entry: string;
27
27
  /**
28
28
  * Effective (including `sub`), Actor, and `effective.isDelegated`. Null
@@ -3,7 +3,7 @@
3
3
  // keeps no App Key and no user token.
4
4
 
5
5
  import { describe, expect, it, vi } from "vitest";
6
- import { callService, platformError } from "../src/call-service";
6
+ import { callService, PLATFORM_ERROR_CODES, platformError } from "../src/call-service";
7
7
  import { makeHarness, serviceRefusal } from "./harness";
8
8
 
9
9
  const env = {
@@ -73,7 +73,7 @@ describe("callService", () => {
73
73
 
74
74
  await callService(
75
75
  h.testEnv,
76
- "shop/orders",
76
+ "orders",
77
77
  "items/1?limit=2",
78
78
  { method: "GET", headers: { "x-pple-user-token": "smuggled" } },
79
79
  { fetchImpl: h.fetchImpl },
@@ -81,7 +81,7 @@ describe("callService", () => {
81
81
 
82
82
  expect(userToken).toBeNull();
83
83
  expect(h.calls.services).toEqual([
84
- { path: "/shop/orders/items/1?limit=2", method: "GET", headers: {} },
84
+ { path: "/orders/items/1?limit=2", method: "GET", headers: {} },
85
85
  ]);
86
86
  });
87
87
 
@@ -108,14 +108,91 @@ describe("callService", () => {
108
108
  const fetchImpl = vi.fn<typeof fetch>(async () => new Response("from-injected"));
109
109
  const res = await callService(
110
110
  { ...env, DEV_PERSONA: "hq-staff", DEV_REGISTRY_ERROR: "not_granted" },
111
- "shop/orders",
111
+ "orders",
112
112
  "/items/1",
113
113
  { method: "GET" },
114
114
  { userToken: "t", fetchImpl },
115
115
  );
116
116
  expect(await res.text()).toBe("from-injected");
117
117
  expect(fetchImpl).toHaveBeenCalledOnce();
118
- expect(String(fetchImpl.mock.calls[0]?.[0])).toBe("https://services.test/shop/orders/items/1");
118
+ expect(String(fetchImpl.mock.calls[0]?.[0])).toBe("https://services.test/orders/items/1");
119
+ });
120
+
121
+ it("calls an app's entry by its bare name, with no provider in the URL", async () => {
122
+ const fetchImpl = vi.fn<typeof fetch>(async () => new Response("ok"));
123
+ await callService(env, "branch-list", "/offices", { method: "GET" }, { fetchImpl });
124
+ expect(String(fetchImpl.mock.calls[0]?.[0])).toBe("https://services.test/branch-list/offices");
125
+ });
126
+
127
+ it('builds services.<domain>/platform/sms/… for the platform\'s "platform/sms"', async () => {
128
+ const fetchImpl = vi.fn<typeof fetch>(async () => new Response("ok"));
129
+ await callService(env, "platform/sms", "", { method: "POST" }, { userToken: "tok", fetchImpl });
130
+ await callService(env, "platform/sms", "/send", { method: "POST" }, { fetchImpl });
131
+ await callService(env, "platform/legal-identity", "?dry=1", { method: "POST" }, { fetchImpl });
132
+ expect(fetchImpl.mock.calls.map((call) => String(call[0]))).toEqual([
133
+ "https://services.test/platform/sms",
134
+ "https://services.test/platform/sms/send",
135
+ "https://services.test/platform/legal-identity?dry=1",
136
+ ]);
137
+ const headers = new Headers(fetchImpl.mock.calls[0]?.[1]?.headers);
138
+ expect(headers.get("authorization")).toBe("Bearer app-key");
139
+ expect(headers.get("x-pple-user-token")).toBe("tok");
140
+ });
141
+
142
+ it("builds services.<domain>/<full name>/… for a Namespace name, up to four segments", async () => {
143
+ const fetchImpl = vi.fn<typeof fetch>(async () => new Response("ok"));
144
+ await callService(env, "election/2027/score", "/units/7?limit=2", { method: "GET" }, { fetchImpl });
145
+ await callService(env, "election/score", "", {}, { fetchImpl });
146
+ await callService(env, "election/2027/regional/score", "units", {}, { fetchImpl });
147
+ expect(fetchImpl.mock.calls.map((call) => String(call[0]))).toEqual([
148
+ "https://services.test/election/2027/score/units/7?limit=2",
149
+ "https://services.test/election/score",
150
+ "https://services.test/election/2027/regional/score/units",
151
+ ]);
152
+ });
153
+
154
+ it("sends the App Key for a full name, as for a bare one", async () => {
155
+ const fetchImpl = vi.fn<typeof fetch>(async () => new Response("ok"));
156
+ await callService(env, "election/score", "/", {}, { userToken: "tok", fetchImpl });
157
+ const init = fetchImpl.mock.calls[0]?.[1];
158
+ const headers = new Headers(init?.headers);
159
+ expect(headers.get("authorization")).toBe("Bearer app-key");
160
+ expect(headers.get("x-pple-user-token")).toBe("tok");
161
+ });
162
+
163
+ it.each([
164
+ ["health", /"health" is reserved/],
165
+ ["overlay/x", /"overlay" is reserved/],
166
+ ["platform", /"platform" belongs to the platform.*such as "platform\/sms"/],
167
+ ])('rejects the reserved name "%s"', async (id, message) => {
168
+ const fetchImpl = vi.fn<typeof fetch>();
169
+ await expect(callService(env, id, "", {}, { fetchImpl })).rejects.toThrow(message);
170
+ expect(fetchImpl).not.toHaveBeenCalled();
171
+ });
172
+
173
+ it.each([
174
+ "",
175
+ "Election/score",
176
+ "election//score",
177
+ "/election/score",
178
+ "election/score/",
179
+ "election/ score",
180
+ "election/a/b/c/d",
181
+ "-election/score",
182
+ "election_2027/score",
183
+ `${"a".repeat(64)}/score`,
184
+ `${"a".repeat(63)}/${"b".repeat(63)}/c`,
185
+ ])('rejects the name "%s" as not an entry name', async (id) => {
186
+ const fetchImpl = vi.fn<typeof fetch>();
187
+ await expect(callService(env, id, "", {}, { fetchImpl })).rejects.toThrow(/is not an entry name/);
188
+ expect(fetchImpl).not.toHaveBeenCalled();
189
+ });
190
+
191
+ it("accepts the longest names the validator allows", async () => {
192
+ const fetchImpl = vi.fn<typeof fetch>(async () => new Response("ok"));
193
+ const full = `${"a".repeat(63)}/${"b".repeat(63)}`; // 127 characters
194
+ await callService(env, full, "", {}, { fetchImpl });
195
+ expect(String(fetchImpl.mock.calls[0]?.[0])).toBe(`https://services.test/${full}`);
119
196
  });
120
197
 
121
198
  it("does not call out without the services URL or the App Key", async () => {
@@ -130,6 +207,38 @@ describe("callService", () => {
130
207
  });
131
208
  });
132
209
 
210
+ describe("a renamed entry", () => {
211
+ // pple-services answers an old full name with 410, `x-pple-error: renamed`
212
+ // and the new name in the body (ADR-0032, #346).
213
+ const renamedAnswer = () =>
214
+ Response.json(
215
+ {
216
+ error: "renamed",
217
+ renamed: "entry",
218
+ renamedTo: "vote/score",
219
+ message: "renamed to vote/score",
220
+ },
221
+ { status: 410, headers: { "x-pple-error": "renamed" } },
222
+ );
223
+
224
+ it("is a typed platform refusal on callService, and the body still names the new entry", async () => {
225
+ const h = makeHarness({ services: renamedAnswer }, env);
226
+
227
+ const res = await callService(h.testEnv, "election/score", "/results", { method: "GET" }, {
228
+ fetchImpl: h.fetchImpl,
229
+ });
230
+
231
+ expect(h.calls.services[0]?.path).toBe("/election/score/results");
232
+ expect(res.status).toBe(410);
233
+ expect(platformError(res)).toBe("renamed");
234
+ expect(await res.json()).toMatchObject({ renamedTo: "vote/score" });
235
+ });
236
+
237
+ it("is listed with the other codes", () => {
238
+ expect(PLATFORM_ERROR_CODES).toContain("renamed");
239
+ });
240
+ });
241
+
133
242
  describe("services fake", () => {
134
243
  it("answers as any Provider and refuses with any x-pple-error code", async () => {
135
244
  const codes = [
@@ -141,13 +250,14 @@ describe("services fake", () => {
141
250
  "identity_unavailable",
142
251
  "provider_unavailable",
143
252
  "provider_timeout",
253
+ "renamed",
144
254
  "no_mock",
145
255
  "made_up",
146
256
  ];
147
257
  let next = Response.json({ items: ["a"] });
148
258
  const h = makeHarness({ services: () => next }, env);
149
259
 
150
- const answered = await callService(h.testEnv, "shop/catalog", "/search", { method: "GET" }, {
260
+ const answered = await callService(h.testEnv, "catalog", "/search", { method: "GET" }, {
151
261
  fetchImpl: h.fetchImpl,
152
262
  });
153
263
  expect(answered.status).toBe(200);
@@ -156,7 +266,7 @@ describe("services fake", () => {
156
266
 
157
267
  for (const code of codes) {
158
268
  next = serviceRefusal(code, 418);
159
- const res = await callService(h.testEnv, "shop/catalog", "", { method: "POST" }, {
269
+ const res = await callService(h.testEnv, "catalog", "", { method: "POST" }, {
160
270
  userToken: "t",
161
271
  fetchImpl: h.fetchImpl,
162
272
  });
@@ -168,7 +278,7 @@ describe("services fake", () => {
168
278
  else expect(known).toBe(code);
169
279
  }
170
280
 
171
- expect(h.calls.services[0]).toEqual({ path: "/shop/catalog/search", method: "GET", headers: {} });
281
+ expect(h.calls.services[0]).toEqual({ path: "/catalog/search", method: "GET", headers: {} });
172
282
  expect(h.calls.services).toHaveLength(1 + codes.length);
173
283
  for (const call of h.calls.services) {
174
284
  expect(call.headers).not.toHaveProperty("authorization");