@rocicorp/zero 1.3.0-canary.0 → 1.3.0-canary.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  var package_default = {
2
2
  name: "@rocicorp/zero",
3
- version: "1.3.0-canary.0",
3
+ version: "1.3.0-canary.1",
4
4
  description: "Zero is a web framework for serverless web development.",
5
5
  author: "Rocicorp, Inc.",
6
6
  repository: {
@@ -1 +1 @@
1
- {"version":3,"file":"package.js","names":[],"sources":["../../package.json"],"sourcesContent":["{\n \"name\": \"@rocicorp/zero\",\n \"version\": \"1.3.0-canary.0\",\n \"description\": \"Zero is a web framework for serverless web development.\",\n \"author\": \"Rocicorp, Inc.\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/rocicorp/mono.git\",\n \"directory\": \"packages/zero\"\n },\n \"license\": \"Apache-2.0\",\n \"homepage\": \"https://zero.rocicorp.dev\",\n \"bugs\": {\n \"url\": \"https://bugs.rocicorp.dev\"\n },\n \"scripts\": {\n \"build\": \"node --experimental-strip-types --no-warnings tool/build.ts\",\n \"build:watch\": \"node --experimental-strip-types --no-warnings tool/build.ts --watch\",\n \"check-types\": \"tsc -p tsconfig.client.json && tsc -p tsconfig.server.json\",\n \"check-types:client:watch\": \"tsc -p tsconfig.client.json --watch\",\n \"check-types:server:watch\": \"tsc -p tsconfig.server.json --watch\",\n \"format\": \"oxfmt .\",\n \"check-format\": \"oxfmt --check .\",\n \"lint\": \"oxlint --type-aware src/\",\n \"docs\": \"node --experimental-strip-types --no-warnings tool/generate-docs.ts\",\n \"docs:server\": \"node --watch --experimental-strip-types --no-warnings tool/generate-docs.ts --server\"\n },\n \"dependencies\": {\n \"@badrap/valita\": \"0.3.11\",\n \"@databases/escape-identifier\": \"^1.0.3\",\n \"@databases/sql\": \"^3.3.0\",\n \"@dotenvx/dotenvx\": \"^1.39.0\",\n \"@drdgvhbh/postgres-error-codes\": \"^0.0.6\",\n \"@fastify/cors\": \"^10.0.0\",\n \"@fastify/websocket\": \"^11.0.0\",\n \"@google-cloud/precise-date\": \"^4.0.0\",\n \"@opentelemetry/api\": \"^1.9.0\",\n \"@opentelemetry/api-logs\": \"^0.203.0\",\n \"@opentelemetry/auto-instrumentations-node\": \"^0.62.0\",\n \"@opentelemetry/exporter-metrics-otlp-http\": \"^0.203.0\",\n \"@opentelemetry/resources\": \"^2.0.1\",\n \"@opentelemetry/sdk-metrics\": \"^2.0.1\",\n \"@opentelemetry/sdk-node\": \"^0.203.0\",\n \"@opentelemetry/sdk-trace-node\": \"^2.0.1\",\n \"@postgresql-typed/oids\": \"^0.2.0\",\n \"@rocicorp/lock\": \"^1.0.4\",\n \"@rocicorp/logger\": \"^5.4.0\",\n \"@rocicorp/resolver\": \"^1.0.2\",\n \"@rocicorp/zero-sqlite3\": \"^1.0.15\",\n \"@standard-schema/spec\": \"^1.0.0\",\n \"@types/basic-auth\": \"^1.1.8\",\n \"@types/ws\": \"^8.5.12\",\n \"basic-auth\": \"^2.0.1\",\n \"chalk-template\": \"^1.1.0\",\n \"chokidar\": \"^4.0.1\",\n \"cloudevents\": \"^10.0.0\",\n \"command-line-args\": \"^6.0.1\",\n \"command-line-usage\": \"^7.0.3\",\n \"compare-utf8\": \"^0.2.0\",\n \"defu\": \"^6.1.4\",\n \"eventemitter3\": \"^5.0.1\",\n \"fastify\": \"^5.0.0\",\n \"is-in-subnet\": \"^4.0.1\",\n \"jose\": \"^5.9.3\",\n \"js-xxhash\": \"^4.0.0\",\n \"json-custom-numbers\": \"^3.1.1\",\n \"kasi\": \"^1.1.0\",\n \"nanoid\": \"^5.1.2\",\n \"oxfmt\": \"^0.44.0\",\n \"parse-prometheus-text-format\": \"^1.1.1\",\n \"pg-format\": \"npm:pg-format-fix@^1.0.5\",\n \"postgres\": \"3.4.7\",\n \"semver\": \"^7.5.4\",\n \"tsx\": \"^4.21.0\",\n \"url-pattern\": \"^1.0.3\",\n \"urlpattern-polyfill\": \"^10.1.0\",\n \"ws\": \"^8.18.1\"\n },\n \"devDependencies\": {\n \"@op-engineering/op-sqlite\": \">=15\",\n \"@vitest/runner\": \"4.1.3\",\n \"analyze-query\": \"0.0.0\",\n \"ast-to-zql\": \"0.0.0\",\n \"expo-sqlite\": \">=15\",\n \"replicache\": \"15.2.1\",\n \"shared\": \"0.0.0\",\n \"syncpack\": \"^14.3.0\",\n \"typedoc\": \"^0.28.17\",\n \"typedoc-plugin-markdown\": \"^4.10.0\",\n \"typescript\": \"~6.0.2\",\n \"vite\": \"8.0.3\",\n \"vitest\": \"4.1.3\",\n \"zero-cache\": \"0.0.0\",\n \"zero-client\": \"0.0.0\",\n \"zero-pg\": \"0.0.0\",\n \"zero-protocol\": \"0.0.0\",\n \"zero-react\": \"0.0.0\",\n \"zero-server\": \"0.0.0\",\n \"zero-solid\": \"0.0.0\",\n \"zqlite\": \"0.0.0\"\n },\n \"peerDependencies\": {\n \"@op-engineering/op-sqlite\": \">=15\",\n \"expo-sqlite\": \">=15\"\n },\n \"peerDependenciesMeta\": {\n \"expo-sqlite\": {\n \"optional\": true\n },\n \"@op-engineering/op-sqlite\": {\n \"optional\": true\n }\n },\n \"type\": \"module\",\n \"main\": \"out/zero/src/zero.js\",\n \"module\": \"out/zero/src/zero.js\",\n \"types\": \"out/zero/src/zero.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./out/zero/src/zero.d.ts\",\n \"default\": \"./out/zero/src/zero.js\"\n },\n \"./bindings\": {\n \"types\": \"./out/zero/src/bindings.d.ts\",\n \"default\": \"./out/zero/src/bindings.js\"\n },\n \"./change-protocol/v0\": {\n \"types\": \"./out/zero/src/change-protocol/v0.d.ts\",\n \"default\": \"./out/zero/src/change-protocol/v0.js\"\n },\n \"./expo-sqlite\": {\n \"types\": \"./out/zero/src/expo-sqlite.d.ts\",\n \"default\": \"./out/zero/src/expo-sqlite.js\"\n },\n \"./op-sqlite\": {\n \"types\": \"./out/zero/src/op-sqlite.d.ts\",\n \"default\": \"./out/zero/src/op-sqlite.js\"\n },\n \"./pg\": {\n \"types\": \"./out/zero/src/pg.d.ts\",\n \"default\": \"./out/zero/src/pg.js\"\n },\n \"./react\": {\n \"types\": \"./out/zero/src/react.d.ts\",\n \"default\": \"./out/zero/src/react.js\"\n },\n \"./react-native\": {\n \"types\": \"./out/zero/src/react-native.d.ts\",\n \"default\": \"./out/zero/src/react-native.js\"\n },\n \"./server\": {\n \"types\": \"./out/zero/src/server.d.ts\",\n \"default\": \"./out/zero/src/server.js\"\n },\n \"./server/adapters/drizzle\": {\n \"types\": \"./out/zero/src/adapters/drizzle.d.ts\",\n \"default\": \"./out/zero/src/adapters/drizzle.js\"\n },\n \"./server/adapters/prisma\": {\n \"types\": \"./out/zero/src/adapters/prisma.d.ts\",\n \"default\": \"./out/zero/src/adapters/prisma.js\"\n },\n \"./server/adapters/pg\": {\n \"types\": \"./out/zero/src/adapters/pg.d.ts\",\n \"default\": \"./out/zero/src/adapters/pg.js\"\n },\n \"./server/adapters/postgresjs\": {\n \"types\": \"./out/zero/src/adapters/postgresjs.d.ts\",\n \"default\": \"./out/zero/src/adapters/postgresjs.js\"\n },\n \"./solid\": {\n \"types\": \"./out/zero/src/solid.d.ts\",\n \"default\": \"./out/zero/src/solid.js\"\n },\n \"./sqlite\": {\n \"types\": \"./out/zero/src/sqlite.d.ts\",\n \"default\": \"./out/zero/src/sqlite.js\"\n },\n \"./zqlite\": {\n \"types\": \"./out/zero/src/zqlite.d.ts\",\n \"default\": \"./out/zero/src/zqlite.js\"\n }\n },\n \"bin\": {\n \"zero-build-schema\": \"./out/zero/src/build-schema.js\",\n \"zero-cache\": \"./out/zero/src/cli.js\",\n \"zero-cache-dev\": \"./out/zero/src/zero-cache-dev.js\",\n \"zero-deploy-permissions\": \"./out/zero/src/deploy-permissions.js\",\n \"zero-out\": \"./out/zero/src/zero-out.js\",\n \"ast-to-zql\": \"./out/zero/src/ast-to-zql.js\",\n \"analyze-query\": \"./out/zero/src/analyze-query.js\",\n \"transform-query\": \"./out/zero/src/transform-query.js\"\n },\n \"engines\": {\n \"node\": \">=22\"\n },\n \"files\": [\n \"out\",\n \"!*.tsbuildinfo\"\n ]\n}"],"mappings":""}
1
+ {"version":3,"file":"package.js","names":[],"sources":["../../package.json"],"sourcesContent":["{\n \"name\": \"@rocicorp/zero\",\n \"version\": \"1.3.0-canary.1\",\n \"description\": \"Zero is a web framework for serverless web development.\",\n \"author\": \"Rocicorp, Inc.\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/rocicorp/mono.git\",\n \"directory\": \"packages/zero\"\n },\n \"license\": \"Apache-2.0\",\n \"homepage\": \"https://zero.rocicorp.dev\",\n \"bugs\": {\n \"url\": \"https://bugs.rocicorp.dev\"\n },\n \"scripts\": {\n \"build\": \"node --experimental-strip-types --no-warnings tool/build.ts\",\n \"build:watch\": \"node --experimental-strip-types --no-warnings tool/build.ts --watch\",\n \"check-types\": \"tsc -p tsconfig.client.json && tsc -p tsconfig.server.json\",\n \"check-types:client:watch\": \"tsc -p tsconfig.client.json --watch\",\n \"check-types:server:watch\": \"tsc -p tsconfig.server.json --watch\",\n \"format\": \"oxfmt .\",\n \"check-format\": \"oxfmt --check .\",\n \"lint\": \"oxlint --type-aware src/\",\n \"docs\": \"node --experimental-strip-types --no-warnings tool/generate-docs.ts\",\n \"docs:server\": \"node --watch --experimental-strip-types --no-warnings tool/generate-docs.ts --server\"\n },\n \"dependencies\": {\n \"@badrap/valita\": \"0.3.11\",\n \"@databases/escape-identifier\": \"^1.0.3\",\n \"@databases/sql\": \"^3.3.0\",\n \"@dotenvx/dotenvx\": \"^1.39.0\",\n \"@drdgvhbh/postgres-error-codes\": \"^0.0.6\",\n \"@fastify/cors\": \"^10.0.0\",\n \"@fastify/websocket\": \"^11.0.0\",\n \"@google-cloud/precise-date\": \"^4.0.0\",\n \"@opentelemetry/api\": \"^1.9.0\",\n \"@opentelemetry/api-logs\": \"^0.203.0\",\n \"@opentelemetry/auto-instrumentations-node\": \"^0.62.0\",\n \"@opentelemetry/exporter-metrics-otlp-http\": \"^0.203.0\",\n \"@opentelemetry/resources\": \"^2.0.1\",\n \"@opentelemetry/sdk-metrics\": \"^2.0.1\",\n \"@opentelemetry/sdk-node\": \"^0.203.0\",\n \"@opentelemetry/sdk-trace-node\": \"^2.0.1\",\n \"@postgresql-typed/oids\": \"^0.2.0\",\n \"@rocicorp/lock\": \"^1.0.4\",\n \"@rocicorp/logger\": \"^5.4.0\",\n \"@rocicorp/resolver\": \"^1.0.2\",\n \"@rocicorp/zero-sqlite3\": \"^1.0.15\",\n \"@standard-schema/spec\": \"^1.0.0\",\n \"@types/basic-auth\": \"^1.1.8\",\n \"@types/ws\": \"^8.5.12\",\n \"basic-auth\": \"^2.0.1\",\n \"chalk-template\": \"^1.1.0\",\n \"chokidar\": \"^4.0.1\",\n \"cloudevents\": \"^10.0.0\",\n \"command-line-args\": \"^6.0.1\",\n \"command-line-usage\": \"^7.0.3\",\n \"compare-utf8\": \"^0.2.0\",\n \"defu\": \"^6.1.4\",\n \"eventemitter3\": \"^5.0.1\",\n \"fastify\": \"^5.0.0\",\n \"is-in-subnet\": \"^4.0.1\",\n \"jose\": \"^5.9.3\",\n \"js-xxhash\": \"^4.0.0\",\n \"json-custom-numbers\": \"^3.1.1\",\n \"kasi\": \"^1.1.0\",\n \"nanoid\": \"^5.1.2\",\n \"oxfmt\": \"^0.44.0\",\n \"parse-prometheus-text-format\": \"^1.1.1\",\n \"pg-format\": \"npm:pg-format-fix@^1.0.5\",\n \"postgres\": \"3.4.7\",\n \"semver\": \"^7.5.4\",\n \"tsx\": \"^4.21.0\",\n \"url-pattern\": \"^1.0.3\",\n \"urlpattern-polyfill\": \"^10.1.0\",\n \"ws\": \"^8.18.1\"\n },\n \"devDependencies\": {\n \"@op-engineering/op-sqlite\": \">=15\",\n \"@vitest/runner\": \"4.1.3\",\n \"analyze-query\": \"0.0.0\",\n \"ast-to-zql\": \"0.0.0\",\n \"expo-sqlite\": \">=15\",\n \"replicache\": \"15.2.1\",\n \"shared\": \"0.0.0\",\n \"syncpack\": \"^14.3.0\",\n \"typedoc\": \"^0.28.17\",\n \"typedoc-plugin-markdown\": \"^4.10.0\",\n \"typescript\": \"~6.0.2\",\n \"vite\": \"8.0.3\",\n \"vitest\": \"4.1.3\",\n \"zero-cache\": \"0.0.0\",\n \"zero-client\": \"0.0.0\",\n \"zero-pg\": \"0.0.0\",\n \"zero-protocol\": \"0.0.0\",\n \"zero-react\": \"0.0.0\",\n \"zero-server\": \"0.0.0\",\n \"zero-solid\": \"0.0.0\",\n \"zqlite\": \"0.0.0\"\n },\n \"peerDependencies\": {\n \"@op-engineering/op-sqlite\": \">=15\",\n \"expo-sqlite\": \">=15\"\n },\n \"peerDependenciesMeta\": {\n \"expo-sqlite\": {\n \"optional\": true\n },\n \"@op-engineering/op-sqlite\": {\n \"optional\": true\n }\n },\n \"type\": \"module\",\n \"main\": \"out/zero/src/zero.js\",\n \"module\": \"out/zero/src/zero.js\",\n \"types\": \"out/zero/src/zero.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./out/zero/src/zero.d.ts\",\n \"default\": \"./out/zero/src/zero.js\"\n },\n \"./bindings\": {\n \"types\": \"./out/zero/src/bindings.d.ts\",\n \"default\": \"./out/zero/src/bindings.js\"\n },\n \"./change-protocol/v0\": {\n \"types\": \"./out/zero/src/change-protocol/v0.d.ts\",\n \"default\": \"./out/zero/src/change-protocol/v0.js\"\n },\n \"./expo-sqlite\": {\n \"types\": \"./out/zero/src/expo-sqlite.d.ts\",\n \"default\": \"./out/zero/src/expo-sqlite.js\"\n },\n \"./op-sqlite\": {\n \"types\": \"./out/zero/src/op-sqlite.d.ts\",\n \"default\": \"./out/zero/src/op-sqlite.js\"\n },\n \"./pg\": {\n \"types\": \"./out/zero/src/pg.d.ts\",\n \"default\": \"./out/zero/src/pg.js\"\n },\n \"./react\": {\n \"types\": \"./out/zero/src/react.d.ts\",\n \"default\": \"./out/zero/src/react.js\"\n },\n \"./react-native\": {\n \"types\": \"./out/zero/src/react-native.d.ts\",\n \"default\": \"./out/zero/src/react-native.js\"\n },\n \"./server\": {\n \"types\": \"./out/zero/src/server.d.ts\",\n \"default\": \"./out/zero/src/server.js\"\n },\n \"./server/adapters/drizzle\": {\n \"types\": \"./out/zero/src/adapters/drizzle.d.ts\",\n \"default\": \"./out/zero/src/adapters/drizzle.js\"\n },\n \"./server/adapters/prisma\": {\n \"types\": \"./out/zero/src/adapters/prisma.d.ts\",\n \"default\": \"./out/zero/src/adapters/prisma.js\"\n },\n \"./server/adapters/pg\": {\n \"types\": \"./out/zero/src/adapters/pg.d.ts\",\n \"default\": \"./out/zero/src/adapters/pg.js\"\n },\n \"./server/adapters/postgresjs\": {\n \"types\": \"./out/zero/src/adapters/postgresjs.d.ts\",\n \"default\": \"./out/zero/src/adapters/postgresjs.js\"\n },\n \"./solid\": {\n \"types\": \"./out/zero/src/solid.d.ts\",\n \"default\": \"./out/zero/src/solid.js\"\n },\n \"./sqlite\": {\n \"types\": \"./out/zero/src/sqlite.d.ts\",\n \"default\": \"./out/zero/src/sqlite.js\"\n },\n \"./zqlite\": {\n \"types\": \"./out/zero/src/zqlite.d.ts\",\n \"default\": \"./out/zero/src/zqlite.js\"\n }\n },\n \"bin\": {\n \"zero-build-schema\": \"./out/zero/src/build-schema.js\",\n \"zero-cache\": \"./out/zero/src/cli.js\",\n \"zero-cache-dev\": \"./out/zero/src/zero-cache-dev.js\",\n \"zero-deploy-permissions\": \"./out/zero/src/deploy-permissions.js\",\n \"zero-out\": \"./out/zero/src/zero-out.js\",\n \"ast-to-zql\": \"./out/zero/src/ast-to-zql.js\",\n \"analyze-query\": \"./out/zero/src/analyze-query.js\",\n \"transform-query\": \"./out/zero/src/transform-query.js\"\n },\n \"engines\": {\n \"node\": \">=22\"\n },\n \"files\": [\n \"out\",\n \"!*.tsbuildinfo\"\n ]\n}"],"mappings":""}
@@ -2,8 +2,8 @@ import type { LogContext } from '@rocicorp/logger';
2
2
  import 'urlpattern-polyfill';
3
3
  import type { ReadonlyJSONValue } from '../../../shared/src/json.ts';
4
4
  import { type Type } from '../../../shared/src/valita.ts';
5
- import { type ShardID } from '../types/shards.ts';
6
5
  import type { ConnectionContext } from '../services/view-syncer/connection-context-manager.ts';
6
+ import { type ShardID } from '../types/shards.ts';
7
7
  /**
8
8
  * Compiles and validates a URLPattern from configuration.
9
9
  *
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/custom/fetch.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,UAAU,EAAW,MAAM,kBAAkB,CAAC;AAC3D,OAAO,qBAAqB,CAAC;AAG7B,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,6BAA6B,CAAC;AAEnE,OAAO,EAAC,KAAK,IAAI,EAAC,MAAM,+BAA+B,CAAC;AAMxD,OAAO,EAAiB,KAAK,OAAO,EAAC,MAAM,oBAAoB,CAAC;AAEhE,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,uDAAuD,CAAC;AAK7F;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,GAAG,UAAU,CAQ7D;AA4BD,eAAO,MAAM,cAAc,GACzB,KAAK,QAAQ,EACb,IAAI,UAAU,KACb,OAAO,CAAC,MAAM,GAAG,SAAS,CAkB5B,CAAC;AAIF,wBAAsB,kBAAkB,CAAC,UAAU,SAAS,IAAI,EAC9D,SAAS,EAAE,UAAU,EACrB,MAAM,EAAE,MAAM,GAAG,WAAW,EAC5B,EAAE,EAAE,UAAU,EACd,GAAG,EAAE,iBAAiB,EACtB,KAAK,EAAE,OAAO,EACd,IAAI,EAAE,iBAAiB,uDA2NxB;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,QAAQ,CACtB,GAAG,EAAE,MAAM,EACX,kBAAkB,EAAE,UAAU,EAAE,GAC/B,OAAO,CAOT"}
1
+ {"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/custom/fetch.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,UAAU,EAAW,MAAM,kBAAkB,CAAC;AAC3D,OAAO,qBAAqB,CAAC;AAG7B,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,6BAA6B,CAAC;AAInE,OAAO,EAAC,KAAK,IAAI,EAAC,MAAM,+BAA+B,CAAC;AAKxD,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,uDAAuD,CAAC;AAE7F,OAAO,EAAiB,KAAK,OAAO,EAAC,MAAM,oBAAoB,CAAC;AAIhE;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,GAAG,UAAU,CAQ7D;AA4BD,eAAO,MAAM,cAAc,GACzB,KAAK,QAAQ,EACb,IAAI,UAAU,KACb,OAAO,CAAC,MAAM,GAAG,SAAS,CAkB5B,CAAC;AAIF,wBAAsB,kBAAkB,CAAC,UAAU,SAAS,IAAI,EAC9D,SAAS,EAAE,UAAU,EACrB,MAAM,EAAE,MAAM,GAAG,WAAW,EAC5B,EAAE,EAAE,UAAU,EACd,GAAG,EAAE,iBAAiB,EACtB,KAAK,EAAE,OAAO,EACd,IAAI,EAAE,iBAAiB,uDAwNxB;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,QAAQ,CACtB,GAAG,EAAE,MAAM,EACX,kBAAkB,EAAE,UAAU,EAAE,GAC/B,OAAO,CAOT"}
@@ -76,7 +76,6 @@ async function fetchFromAPIServer(validator, source, lc, ctx, shard, body) {
76
76
  const headers = { "Content-Type": "application/json" };
77
77
  if (headerOptions.apiKey) headers["X-Api-Key"] = headerOptions.apiKey;
78
78
  Object.assign(headers, filterCustomHeaders(headerOptions.customHeaders, headerOptions.allowedClientHeaders));
79
- if (ctx.userID) headers["X-User-ID"] = ctx.userID;
80
79
  if (ctx.auth?.raw) headers["Authorization"] = `Bearer ${ctx.auth.raw}`;
81
80
  if (headerOptions.cookie) headers["Cookie"] = headerOptions.cookie;
82
81
  if (headerOptions.origin) headers["Origin"] = headerOptions.origin;
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.js","names":[],"sources":["../../../../../zero-cache/src/custom/fetch.ts"],"sourcesContent":["import {context, propagation} from '@opentelemetry/api';\nimport type {LogContext, LogLevel} from '@rocicorp/logger';\nimport 'urlpattern-polyfill';\nimport {assert, unreachable} from '../../../shared/src/asserts.ts';\nimport {getErrorMessage} from '../../../shared/src/error.ts';\nimport type {ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport {sleep} from '../../../shared/src/sleep.ts';\nimport {type Type} from '../../../shared/src/valita.ts';\nimport {ErrorKind} from '../../../zero-protocol/src/error-kind.ts';\nimport {ErrorOrigin} from '../../../zero-protocol/src/error-origin.ts';\nimport {ErrorReason} from '../../../zero-protocol/src/error-reason.ts';\nimport {isProtocolError} from '../../../zero-protocol/src/error.ts';\nimport {ProtocolErrorWithLevel} from '../types/error-with-level.ts';\nimport {upstreamSchema, type ShardID} from '../types/shards.ts';\nimport {randInt} from '../../../shared/src/rand.ts';\nimport type {ConnectionContext} from '../services/view-syncer/connection-context-manager.ts';\nimport {must} from '../../../shared/src/must.ts';\n\nconst reservedParams = ['schema', 'appID'];\n\n/**\n * Compiles and validates a URLPattern from configuration.\n *\n * Patterns must be full URLs (e.g., \"https://api.example.com/endpoint\").\n * URLPattern automatically sets search and hash to wildcard ('*'),\n * which means query parameters and fragments are ignored during matching.\n *\n * @throws Error if the pattern is an invalid URLPattern\n */\nexport function compileUrlPattern(pattern: string): URLPattern {\n try {\n return new URLPattern(pattern);\n } catch (e) {\n throw new Error(\n `Invalid URLPattern in URL configuration: \"${pattern}\". Error: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n}\n\n/**\n * Filters custom headers based on the allowed headers list.\n * If no allowedHeaders list is specified, no custom headers are forwarded (secure by default).\n * Header names are compared case-insensitively.\n */\nfunction filterCustomHeaders(\n headers: Record<string, string> | undefined,\n allowedHeaders: readonly string[] | undefined,\n): Record<string, string> {\n if (!headers) {\n return {};\n }\n if (!allowedHeaders || allowedHeaders.length === 0) {\n return {};\n }\n\n const allowed = new Set(allowedHeaders.map(h => h.toLowerCase()));\n const filtered: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n if (allowed.has(key.toLowerCase())) {\n filtered[key] = value;\n }\n }\n return filtered;\n}\n\nexport const getBodyPreview = async (\n res: Response,\n lc: LogContext,\n): Promise<string | undefined> => {\n try {\n const body = await res.clone().text();\n if (body.length > 512) {\n return body.slice(0, 512) + '...';\n }\n return body;\n } catch (e) {\n lc.warn?.(\n 'failed to get body preview',\n {\n url: res.url,\n },\n e,\n );\n }\n\n return undefined;\n};\n\nconst MAX_ATTEMPTS = 4;\n\nexport async function fetchFromAPIServer<TValidator extends Type>(\n validator: TValidator,\n source: 'push' | 'transform',\n lc: LogContext,\n ctx: ConnectionContext,\n shard: ShardID,\n body: ReadonlyJSONValue,\n) {\n const fetchFromAPIServerID = randInt(1, Number.MAX_SAFE_INTEGER).toString(36);\n lc = lc\n .withContext('fetchFromAPIServerID', fetchFromAPIServerID)\n .withContext('source', source);\n\n const fetchConfig = source === 'push' ? ctx.pushContext : ctx.queryContext;\n const url = must(\n fetchConfig.url,\n `Fetch config for ${source} is missing URL`,\n );\n const headerOptions = fetchConfig.headerOptions;\n\n lc.debug?.('fetchFromAPIServer called', {\n url,\n });\n\n if (!urlMatch(url, fetchConfig.allowedUrlPatterns ?? [])) {\n throw new ProtocolErrorWithLevel(\n source === 'push'\n ? {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.ZeroCache,\n reason: ErrorReason.Internal,\n message: `URL \"${url}\" is not allowed by the ZERO_MUTATE_URL configuration`,\n mutationIDs: [],\n }\n : {\n kind: ErrorKind.TransformFailed,\n origin: ErrorOrigin.ZeroCache,\n reason: ErrorReason.Internal,\n message: `URL \"${url}\" is not allowed by the ZERO_QUERY_URL configuration`,\n queryIDs: [],\n },\n 'warn',\n );\n }\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (headerOptions.apiKey) {\n headers['X-Api-Key'] = headerOptions.apiKey;\n }\n Object.assign(\n headers,\n filterCustomHeaders(\n headerOptions.customHeaders,\n headerOptions.allowedClientHeaders,\n ),\n );\n if (ctx.userID) {\n headers['X-User-ID'] = ctx.userID;\n }\n if (ctx.auth?.raw) {\n headers['Authorization'] = `Bearer ${ctx.auth.raw}`;\n }\n if (headerOptions.cookie) {\n headers['Cookie'] = headerOptions.cookie;\n }\n if (headerOptions.origin) {\n headers['Origin'] = headerOptions.origin;\n }\n propagation.inject(context.active(), headers);\n\n const urlObj = new URL(url);\n const params = new URLSearchParams(urlObj.search);\n\n for (const reserved of reservedParams) {\n assert(\n !params.has(reserved),\n `The push URL cannot contain the reserved query param \"${reserved}\"`,\n );\n }\n\n params.append('schema', upstreamSchema(shard));\n params.append('appID', shard.appID);\n\n urlObj.search = params.toString();\n\n const finalUrl = urlObj.toString();\n\n for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {\n lc = lc.withContext('fetchFromAPIServerAttempt', attempt);\n lc.debug?.('fetch from API server attempt');\n const shouldRetry = async () => {\n if (attempt < MAX_ATTEMPTS) {\n const delayMs = getBackoffDelayMs(attempt);\n lc.debug?.(`fetch from API server retrying in ${delayMs} ms`);\n await sleep(delayMs);\n return true;\n }\n lc.debug?.('fetch from API server reached max attempts, not retrying');\n return false;\n };\n try {\n const response = await fetch(finalUrl, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const bodyPreview = await getBodyPreview(response, lc);\n lc.warn?.('fetch from API server returned non-OK status', {\n url: finalUrl,\n status: response.status,\n bodyPreview,\n });\n // Bad Gateway or Gateway Timeout indicate the server was not reached\n // We retry these if we have retries remaining.\n if (\n (response.status === 502 || response.status === 504) &&\n (await shouldRetry())\n ) {\n continue;\n }\n\n throw new ProtocolErrorWithLevel(\n source === 'push'\n ? {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.ZeroCache,\n reason: ErrorReason.HTTP,\n status: response.status,\n bodyPreview,\n message: `Fetch from API server returned non-OK status ${response.status}`,\n mutationIDs: [],\n }\n : {\n kind: ErrorKind.TransformFailed,\n origin: ErrorOrigin.ZeroCache,\n reason: ErrorReason.HTTP,\n status: response.status,\n bodyPreview,\n message: `Fetch from API server returned non-OK status ${response.status}`,\n queryIDs: [],\n },\n 'warn',\n );\n }\n\n try {\n const json = await response.json();\n const result = validator.parse(json);\n lc.debug?.('fetch from API server succeeded');\n return result;\n } catch (error) {\n lc.warn?.(\n 'failed to parse response',\n {\n url: finalUrl,\n },\n error,\n );\n\n throw new ProtocolErrorWithLevel(\n source === 'push'\n ? {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.ZeroCache,\n reason: ErrorReason.Parse,\n message: `Failed to parse response from API server: ${getErrorMessage(error)}`,\n mutationIDs: [],\n }\n : {\n kind: ErrorKind.TransformFailed,\n origin: ErrorOrigin.ZeroCache,\n reason: ErrorReason.Parse,\n message: `Failed to parse response from API server: ${getErrorMessage(error)}`,\n queryIDs: [],\n },\n 'warn',\n {cause: error},\n );\n }\n } catch (error) {\n if (isProtocolError(error)) {\n throw error;\n }\n\n const isFetchFailed =\n error instanceof TypeError && error.message === 'fetch failed';\n // unexpected/unknown errors should be logged at 'error' level so they\n // are investigated\n let logLevel: LogLevel = isFetchFailed ? 'warn' : 'error';\n lc[logLevel]?.(\n 'fetch from API server threw error',\n {url: finalUrl},\n error,\n );\n\n if (isFetchFailed && (await shouldRetry())) {\n continue;\n }\n\n throw new ProtocolErrorWithLevel(\n source === 'push'\n ? {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.ZeroCache,\n reason: ErrorReason.Internal,\n message: `Fetch from API server threw error: ${getErrorMessage(error)}`,\n mutationIDs: [],\n }\n : {\n kind: ErrorKind.TransformFailed,\n origin: ErrorOrigin.ZeroCache,\n reason: ErrorReason.Internal,\n message: `Fetch from API server threw error: ${getErrorMessage(error)}`,\n queryIDs: [],\n },\n logLevel,\n {cause: error},\n );\n }\n }\n unreachable();\n}\n\n/**\n * Returns true if the url matches one of the allowedUrlPatterns.\n *\n * URLPattern automatically ignores query parameters and hash fragments during matching\n * because it sets search and hash to wildcard ('*') by default.\n *\n * Example URLPattern patterns:\n * - \"https://api.example.com/endpoint\" - Exact match for a specific URL\n * - \"https://*.example.com/endpoint\" - Matches any single subdomain (e.g., \"https://api.example.com/endpoint\")\n * - \"https://*.*.example.com/endpoint\" - Matches two subdomains (e.g., \"https://api.v1.example.com/endpoint\")\n * - \"https://api.example.com/*\" - Matches any path under /\n * - \"https://api.example.com/:version/endpoint\" - Matches with named parameter (e.g., \"https://api.example.com/v1/endpoint\")\n */\nexport function urlMatch(\n url: string,\n allowedUrlPatterns: URLPattern[],\n): boolean {\n for (const pattern of allowedUrlPatterns) {\n if (pattern.test(url)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Returns the delay in milliseconds for the next retry attempt using exponential backoff with jitter.\n *\n * The delay assumes the first retry is attempt 1.\n * The formula is: `min(1000, 100 * 2^(attempt - 1) + jitter)` where jitter is between 0 and 100ms.\n */\nfunction getBackoffDelayMs(attempt: number): number {\n return Math.min(1000, 100 * Math.pow(2, attempt - 1) + Math.random() * 100);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAkBA,IAAM,iBAAiB,CAAC,UAAU,QAAQ;;;;;;;;;;AAW1C,SAAgB,kBAAkB,SAA6B;AAC7D,KAAI;AACF,SAAO,IAAI,WAAW,QAAQ;UACvB,GAAG;AACV,QAAM,IAAI,MACR,6CAA6C,QAAQ,YAAY,aAAa,QAAQ,EAAE,UAAU,OAAO,EAAE,GAC5G;;;;;;;;AASL,SAAS,oBACP,SACA,gBACwB;AACxB,KAAI,CAAC,QACH,QAAO,EAAE;AAEX,KAAI,CAAC,kBAAkB,eAAe,WAAW,EAC/C,QAAO,EAAE;CAGX,MAAM,UAAU,IAAI,IAAI,eAAe,KAA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,KAAK,IAAI,CACnB,QAAO;AAGX,QAAO;;;;;;;;AAST,SAAS,kBAAkB,SAAyB;AAClD,QAAO,KAAK,IAAI,KAAM,MAAM,KAAK,IAAI,GAAG,UAAU,EAAE,GAAG,KAAK,QAAQ,GAAG,IAAI"}
1
+ {"version":3,"file":"fetch.js","names":[],"sources":["../../../../../zero-cache/src/custom/fetch.ts"],"sourcesContent":["import {context, propagation} from '@opentelemetry/api';\nimport type {LogContext, LogLevel} from '@rocicorp/logger';\nimport 'urlpattern-polyfill';\nimport {assert, unreachable} from '../../../shared/src/asserts.ts';\nimport {getErrorMessage} from '../../../shared/src/error.ts';\nimport type {ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport {randInt} from '../../../shared/src/rand.ts';\nimport {sleep} from '../../../shared/src/sleep.ts';\nimport {type Type} from '../../../shared/src/valita.ts';\nimport {ErrorKind} from '../../../zero-protocol/src/error-kind.ts';\nimport {ErrorOrigin} from '../../../zero-protocol/src/error-origin.ts';\nimport {ErrorReason} from '../../../zero-protocol/src/error-reason.ts';\nimport {isProtocolError} from '../../../zero-protocol/src/error.ts';\nimport type {ConnectionContext} from '../services/view-syncer/connection-context-manager.ts';\nimport {ProtocolErrorWithLevel} from '../types/error-with-level.ts';\nimport {upstreamSchema, type ShardID} from '../types/shards.ts';\n\nconst reservedParams = ['schema', 'appID'];\n\n/**\n * Compiles and validates a URLPattern from configuration.\n *\n * Patterns must be full URLs (e.g., \"https://api.example.com/endpoint\").\n * URLPattern automatically sets search and hash to wildcard ('*'),\n * which means query parameters and fragments are ignored during matching.\n *\n * @throws Error if the pattern is an invalid URLPattern\n */\nexport function compileUrlPattern(pattern: string): URLPattern {\n try {\n return new URLPattern(pattern);\n } catch (e) {\n throw new Error(\n `Invalid URLPattern in URL configuration: \"${pattern}\". Error: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n}\n\n/**\n * Filters custom headers based on the allowed headers list.\n * If no allowedHeaders list is specified, no custom headers are forwarded (secure by default).\n * Header names are compared case-insensitively.\n */\nfunction filterCustomHeaders(\n headers: Record<string, string> | undefined,\n allowedHeaders: readonly string[] | undefined,\n): Record<string, string> {\n if (!headers) {\n return {};\n }\n if (!allowedHeaders || allowedHeaders.length === 0) {\n return {};\n }\n\n const allowed = new Set(allowedHeaders.map(h => h.toLowerCase()));\n const filtered: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n if (allowed.has(key.toLowerCase())) {\n filtered[key] = value;\n }\n }\n return filtered;\n}\n\nexport const getBodyPreview = async (\n res: Response,\n lc: LogContext,\n): Promise<string | undefined> => {\n try {\n const body = await res.clone().text();\n if (body.length > 512) {\n return body.slice(0, 512) + '...';\n }\n return body;\n } catch (e) {\n lc.warn?.(\n 'failed to get body preview',\n {\n url: res.url,\n },\n e,\n );\n }\n\n return undefined;\n};\n\nconst MAX_ATTEMPTS = 4;\n\nexport async function fetchFromAPIServer<TValidator extends Type>(\n validator: TValidator,\n source: 'push' | 'transform',\n lc: LogContext,\n ctx: ConnectionContext,\n shard: ShardID,\n body: ReadonlyJSONValue,\n) {\n const fetchFromAPIServerID = randInt(1, Number.MAX_SAFE_INTEGER).toString(36);\n lc = lc\n .withContext('fetchFromAPIServerID', fetchFromAPIServerID)\n .withContext('source', source);\n\n const fetchConfig = source === 'push' ? ctx.pushContext : ctx.queryContext;\n const url = must(\n fetchConfig.url,\n `Fetch config for ${source} is missing URL`,\n );\n const headerOptions = fetchConfig.headerOptions;\n\n lc.debug?.('fetchFromAPIServer called', {\n url,\n });\n\n if (!urlMatch(url, fetchConfig.allowedUrlPatterns ?? [])) {\n throw new ProtocolErrorWithLevel(\n source === 'push'\n ? {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.ZeroCache,\n reason: ErrorReason.Internal,\n message: `URL \"${url}\" is not allowed by the ZERO_MUTATE_URL configuration`,\n mutationIDs: [],\n }\n : {\n kind: ErrorKind.TransformFailed,\n origin: ErrorOrigin.ZeroCache,\n reason: ErrorReason.Internal,\n message: `URL \"${url}\" is not allowed by the ZERO_QUERY_URL configuration`,\n queryIDs: [],\n },\n 'warn',\n );\n }\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (headerOptions.apiKey) {\n headers['X-Api-Key'] = headerOptions.apiKey;\n }\n Object.assign(\n headers,\n filterCustomHeaders(\n headerOptions.customHeaders,\n headerOptions.allowedClientHeaders,\n ),\n );\n if (ctx.auth?.raw) {\n headers['Authorization'] = `Bearer ${ctx.auth.raw}`;\n }\n if (headerOptions.cookie) {\n headers['Cookie'] = headerOptions.cookie;\n }\n if (headerOptions.origin) {\n headers['Origin'] = headerOptions.origin;\n }\n propagation.inject(context.active(), headers);\n\n const urlObj = new URL(url);\n const params = new URLSearchParams(urlObj.search);\n\n for (const reserved of reservedParams) {\n assert(\n !params.has(reserved),\n `The push URL cannot contain the reserved query param \"${reserved}\"`,\n );\n }\n\n params.append('schema', upstreamSchema(shard));\n params.append('appID', shard.appID);\n\n urlObj.search = params.toString();\n\n const finalUrl = urlObj.toString();\n\n for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {\n lc = lc.withContext('fetchFromAPIServerAttempt', attempt);\n lc.debug?.('fetch from API server attempt');\n const shouldRetry = async () => {\n if (attempt < MAX_ATTEMPTS) {\n const delayMs = getBackoffDelayMs(attempt);\n lc.debug?.(`fetch from API server retrying in ${delayMs} ms`);\n await sleep(delayMs);\n return true;\n }\n lc.debug?.('fetch from API server reached max attempts, not retrying');\n return false;\n };\n try {\n const response = await fetch(finalUrl, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const bodyPreview = await getBodyPreview(response, lc);\n lc.warn?.('fetch from API server returned non-OK status', {\n url: finalUrl,\n status: response.status,\n bodyPreview,\n });\n // Bad Gateway or Gateway Timeout indicate the server was not reached\n // We retry these if we have retries remaining.\n if (\n (response.status === 502 || response.status === 504) &&\n (await shouldRetry())\n ) {\n continue;\n }\n\n throw new ProtocolErrorWithLevel(\n source === 'push'\n ? {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.ZeroCache,\n reason: ErrorReason.HTTP,\n status: response.status,\n bodyPreview,\n message: `Fetch from API server returned non-OK status ${response.status}`,\n mutationIDs: [],\n }\n : {\n kind: ErrorKind.TransformFailed,\n origin: ErrorOrigin.ZeroCache,\n reason: ErrorReason.HTTP,\n status: response.status,\n bodyPreview,\n message: `Fetch from API server returned non-OK status ${response.status}`,\n queryIDs: [],\n },\n 'warn',\n );\n }\n\n try {\n const json = await response.json();\n const result = validator.parse(json);\n lc.debug?.('fetch from API server succeeded');\n return result;\n } catch (error) {\n lc.warn?.(\n 'failed to parse response',\n {\n url: finalUrl,\n },\n error,\n );\n\n throw new ProtocolErrorWithLevel(\n source === 'push'\n ? {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.ZeroCache,\n reason: ErrorReason.Parse,\n message: `Failed to parse response from API server: ${getErrorMessage(error)}`,\n mutationIDs: [],\n }\n : {\n kind: ErrorKind.TransformFailed,\n origin: ErrorOrigin.ZeroCache,\n reason: ErrorReason.Parse,\n message: `Failed to parse response from API server: ${getErrorMessage(error)}`,\n queryIDs: [],\n },\n 'warn',\n {cause: error},\n );\n }\n } catch (error) {\n if (isProtocolError(error)) {\n throw error;\n }\n\n const isFetchFailed =\n error instanceof TypeError && error.message === 'fetch failed';\n // unexpected/unknown errors should be logged at 'error' level so they\n // are investigated\n let logLevel: LogLevel = isFetchFailed ? 'warn' : 'error';\n lc[logLevel]?.(\n 'fetch from API server threw error',\n {url: finalUrl},\n error,\n );\n\n if (isFetchFailed && (await shouldRetry())) {\n continue;\n }\n\n throw new ProtocolErrorWithLevel(\n source === 'push'\n ? {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.ZeroCache,\n reason: ErrorReason.Internal,\n message: `Fetch from API server threw error: ${getErrorMessage(error)}`,\n mutationIDs: [],\n }\n : {\n kind: ErrorKind.TransformFailed,\n origin: ErrorOrigin.ZeroCache,\n reason: ErrorReason.Internal,\n message: `Fetch from API server threw error: ${getErrorMessage(error)}`,\n queryIDs: [],\n },\n logLevel,\n {cause: error},\n );\n }\n }\n unreachable();\n}\n\n/**\n * Returns true if the url matches one of the allowedUrlPatterns.\n *\n * URLPattern automatically ignores query parameters and hash fragments during matching\n * because it sets search and hash to wildcard ('*') by default.\n *\n * Example URLPattern patterns:\n * - \"https://api.example.com/endpoint\" - Exact match for a specific URL\n * - \"https://*.example.com/endpoint\" - Matches any single subdomain (e.g., \"https://api.example.com/endpoint\")\n * - \"https://*.*.example.com/endpoint\" - Matches two subdomains (e.g., \"https://api.v1.example.com/endpoint\")\n * - \"https://api.example.com/*\" - Matches any path under /\n * - \"https://api.example.com/:version/endpoint\" - Matches with named parameter (e.g., \"https://api.example.com/v1/endpoint\")\n */\nexport function urlMatch(\n url: string,\n allowedUrlPatterns: URLPattern[],\n): boolean {\n for (const pattern of allowedUrlPatterns) {\n if (pattern.test(url)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Returns the delay in milliseconds for the next retry attempt using exponential backoff with jitter.\n *\n * The delay assumes the first retry is attempt 1.\n * The formula is: `min(1000, 100 * 2^(attempt - 1) + jitter)` where jitter is between 0 and 100ms.\n */\nfunction getBackoffDelayMs(attempt: number): number {\n return Math.min(1000, 100 * Math.pow(2, attempt - 1) + Math.random() * 100);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAkBA,IAAM,iBAAiB,CAAC,UAAU,QAAQ;;;;;;;;;;AAW1C,SAAgB,kBAAkB,SAA6B;AAC7D,KAAI;AACF,SAAO,IAAI,WAAW,QAAQ;UACvB,GAAG;AACV,QAAM,IAAI,MACR,6CAA6C,QAAQ,YAAY,aAAa,QAAQ,EAAE,UAAU,OAAO,EAAE,GAC5G;;;;;;;;AASL,SAAS,oBACP,SACA,gBACwB;AACxB,KAAI,CAAC,QACH,QAAO,EAAE;AAEX,KAAI,CAAC,kBAAkB,eAAe,WAAW,EAC/C,QAAO,EAAE;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AAK,IAAI,CACnB,QAAO;AAGX,QAAO;;;;;;;;AAST,SAAS,kBAAkB,SAAyB;AAClD,QAAO,KAAK,IAAI,KAAM,MAAM,KAAK,IAAI,GAAG,UAAU,EAAE,GAAG,KAAK,QAAQ,GAAG,IAAI"}
@@ -49,10 +49,6 @@ export type ZeroOptions<S extends BaseDefaultSchema = DefaultSchema, MD extends
49
49
  *
50
50
  * Omit this, or set to `null`, for logged-out clients.
51
51
  *
52
- * This is passed to the query/mutate endpoints via an `X-User-ID` header and
53
- * must be used to validate claimed user identity against the provided auth
54
- * on the server (either token or cookie auth).
55
- *
56
52
  * Each userID gets its own client-side storage so that the app can switch
57
53
  * between users without losing state.
58
54
  */
@@ -1 +1 @@
1
- {"version":3,"file":"options.d.ts","sourceRoot":"","sources":["../../../../../zero-client/src/client/options.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,kBAAkB,CAAC;AAC/C,OAAO,KAAK,EAAC,aAAa,EAAC,MAAM,qCAAqC,CAAC;AACvE,OAAO,KAAK,CAAC,MAAM,+BAA+B,CAAC;AACnD,OAAO,KAAK,EACV,kBAAkB,EAClB,iBAAiB,EACjB,cAAc,EACd,aAAa,EACd,MAAM,0CAA0C,CAAC;AAClD,OAAO,KAAK,EAAC,kBAAkB,EAAC,MAAM,6CAA6C,CAAC;AACpF,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,aAAa,CAAC;AACnD,OAAO,EAAC,sBAAsB,EAAC,MAAM,gCAAgC,CAAC;AAEtE;;GAEG;AACH,MAAM,MAAM,WAAW,CACrB,CAAC,SAAS,iBAAiB,GAAG,aAAa,EAC3C,EAAE,SAAS,iBAAiB,GAAG,SAAS,GAAG,SAAS,EACpD,CAAC,SAAS,kBAAkB,GAAG,cAAc,IAC3C;IACF;;;;;;;;;;OAUG;IACH,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IAErC;;OAEG;IACH,MAAM,CAAC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C,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAC1B,CAAC;IAAC,IAAI,EAAE,sBAAsB,CAAC,cAAc,CAAA;CAAC,GAAG,sBAAsB,CAAC,GACxE,CAAC;IACC,IAAI,EAAE,sBAAsB,CAAC,mBAAmB,CAAC;CAClD,GAAG,sBAAsB,CAAC,GAC3B,CAAC;IACC,IAAI,EAAE,sBAAsB,CAAC,yBAAyB,CAAC;CACxD,GAAG,sBAAsB,CAAC,CAAC;AAEhC,eAAO,MAAM,4BAA4B,EAAE,CAAC,CAAC,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAKzE,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"options.js","names":[],"sources":["../../../../../zero-client/src/client/options.ts"],"sourcesContent":["import type {LogLevel} from '@rocicorp/logger';\nimport type {StoreProvider} from '../../../replicache/src/kv/store.ts';\nimport * as v from '../../../shared/src/valita.ts';\nimport type {\n BaseDefaultContext,\n BaseDefaultSchema,\n DefaultContext,\n DefaultSchema,\n} from '../../../zero-types/src/default-types.ts';\nimport type {AnyMutatorRegistry} from '../../../zql/src/mutate/mutator-registry.ts';\nimport type {CustomMutatorDefs} from './custom.ts';\nimport {UpdateNeededReasonType} from './update-needed-reason-type.ts';\n\n/**\n * Configuration for {@linkcode Zero}.\n */\nexport type ZeroOptions<\n S extends BaseDefaultSchema = DefaultSchema,\n MD extends CustomMutatorDefs | undefined = undefined,\n C extends BaseDefaultContext = DefaultContext,\n> = {\n /**\n * URL to the zero-cache. This can be a simple hostname, e.g.\n * - \"https://myapp-myteam.zero.ms\"\n * or a prefix with a single path component, e.g.\n * - \"https://myapp-myteam.zero.ms/zero\"\n * - \"https://myapp-myteam.zero.ms/db\"\n *\n * The latter is useful for configuring routing rules (e.g. \"/zero/\\*\") when\n * the zero-cache is hosted on the same domain as the application. **Note that\n * only a single path segment is allowed (e.g. it cannot be \"/proxy/zero/\\*\")**.\n */\n cacheURL?: string | null | undefined;\n\n /**\n * @deprecated Use {@linkcode cacheURL} instead.\n */\n server?: string | null | undefined;\n\n /**\n * A token to identify and authenticate the user.\n *\n * Set `auth` to `null` or `undefined` if there is no logged in user.\n *\n * The call to `connect` is handled automatically by the ZeroProvider component\n * for React and SolidJS when the `auth` prop changes.\n *\n * Transitions between authenticated and logged-out states recreate the Zero\n * instance instead.\n *\n * When `auth` changes while connected, Zero refreshes server-side auth context\n * and re-transforms queries without reconnecting.\n *\n * When a 401 or 403 HTTP status code is received from your server, Zero will\n * transition to the `needs-auth` connection state. The app should call\n * `zero.connection.connect({auth: newToken})` with a new token to reconnect.\n */\n auth?: string | null | undefined;\n\n /**\n * A unique identifier for the user.\n *\n * Omit this, or set to `null`, for logged-out clients.\n *\n * This is passed to the query/mutate endpoints via an `X-User-ID` header and\n * must be used to validate claimed user identity against the provided auth\n * on the server (either token or cookie auth).\n *\n * Each userID gets its own client-side storage so that the app can switch\n * between users without losing state.\n */\n userID?: string | null | undefined;\n\n /**\n * Distinguishes the storage used by this Zero instance from that of other\n * instances with the same userID. Useful in the case where the app wants to\n * have multiple Zero instances for the same user for different parts of the\n * app.\n */\n storageKey?: string | undefined;\n\n /**\n * Determines the level of detail at which Zero logs messages about\n * its operation. Messages are logged to the `console`.\n *\n * When this is set to `'debug'`, `'info'` and `'error'` messages are also\n * logged. When set to `'info'`, `'info'` and `'error'` but not\n * `'debug'` messages are logged. When set to `'error'` only `'error'`\n * messages are logged.\n *\n * Default is `'error'`.\n */\n logLevel?: LogLevel | undefined;\n\n /**\n * This defines the schema of the tables used in Zero and their relationships\n * to one another.\n */\n schema: S;\n\n /**\n * `mutators` is a map of custom mutator definitions. The keys are\n * namespaces or names of the mutators. The values are the mutator\n * implementations. Client side mutators must be idempotent as a\n * mutation can be rebased multiple times when folding in authoritative\n * changes from the server to the client.\n *\n * Define mutators using the `defineMutator` function to create type-safe,\n * parameterized mutations. Mutators can be top-level or grouped in namespaces.\n *\n * @example\n * ```ts\n * import {defineMutator} from '@rocicorp/zero';\n *\n * const z = new Zero({\n * schema,\n * userID,\n * mutators: {\n * // Top-level mutator\n * increment: defineMutator(({tx, args}: {tx: Transaction<Schema>, args: {id: string}}) =>\n * tx.mutate.counter.update({id: args.id, value: tx.query.counter.where('id', '=', args.id).value + 1})\n * ),\n * // Namespace with multiple mutators\n * issues: {\n * create: defineMutator(({tx, args}: {tx: Transaction<Schema>, args: {title: string}}) =>\n * tx.mutate.issues.insert({id: nanoid(), title: args.title, status: 'open'})\n * ),\n * close: defineMutator(({tx, args}: {tx: Transaction<Schema>, args: {id: string}}) =>\n * tx.mutate.issues.update({id: args.id, status: 'closed'})\n * ),\n * },\n * },\n * });\n *\n * // Usage\n * await z.mutate.increment({id: 'counter-1'}).client;\n * await z.mutate.issues.create({title: 'New issue'}).client;\n * await z.mutate.issues.close({id: 'issue-123'}).client;\n * ```\n */\n mutators?: MD extends CustomMutatorDefs ? MD : AnyMutatorRegistry | undefined;\n\n /**\n * Custom URL for mutation requests sent to your API server.\n * If not provided, uses the default configured in zero-cache.\n */\n mutateURL?: string | undefined;\n\n /**\n * Custom headers to include in mutation requests sent to your API server.\n * These headers are passed through zero-cache to the mutate endpoint.\n */\n mutateHeaders?: Record<string, string> | undefined;\n\n /**\n * Custom URL for query requests sent to your API server.\n * If not provided, uses the default configured in zero-cache.\n *\n * @deprecated Use {@linkcode queryURL} instead.\n */\n getQueriesURL?: string | undefined;\n\n /**\n * Custom URL for query requests sent to your API server.\n * If not provided, uses the default configured in zero-cache.\n */\n queryURL?: string | undefined;\n\n /**\n * Custom headers to include in query requests sent to your API server.\n * These headers are passed through zero-cache to the query endpoint.\n */\n queryHeaders?: Record<string, string> | undefined;\n\n /**\n * Optional callback that returns a W3C `traceparent` header value for\n * distributed tracing. Called before sending WebSocket messages that\n * trigger API server calls (`push`, `changeDesiredQueries`,\n * `initConnection`).\n *\n * This enables end-to-end trace correlation from your frontend through\n * zero-cache to your API server.\n *\n * @example\n * ```ts\n * import {propagation, context} from '@opentelemetry/api';\n *\n * new Zero({\n * getTraceparent: () => {\n * const carrier: Record<string, string> = {};\n * propagation.inject(context.active(), carrier);\n * return carrier.traceparent;\n * },\n * });\n * ```\n */\n getTraceparent?: (() => string | undefined) | undefined;\n\n /**\n * `onOnlineChange` is called when the Zero instance's online status changes.\n *\n * @deprecated Use {@linkcode Connection.state.subscribe} on the Zero instance instead. e.g.\n * ```ts\n * const zero = new Zero({...});\n * zero.connection.state.subscribe((state) => {\n * console.log('Connection state:', state.name);\n * });\n * ```\n *\n * Or use a hook like {@linkcode useConnectionState} to subscribe to state changes.\n */\n onOnlineChange?: ((online: boolean) => void) | undefined;\n\n /**\n * `onUpdateNeeded` is called when a client code update is needed.\n *\n * See {@link UpdateNeededReason} for why updates can be needed.\n *\n * The default behavior is to reload the page (using `location.reload()`).\n * Provide your own function to prevent the page from\n * reloading automatically. You may want to display a toast to inform the end\n * user there is a new version of your app available and prompt them to\n * refresh.\n */\n onUpdateNeeded?: ((reason: UpdateNeededReason) => void) | undefined;\n\n /**\n * `onClientStateNotFound` is called when this client is no longer able\n * to sync with the zero-cache due to missing synchronization state. This\n * can be because:\n * - the local persistent synchronization state has been garbage collected.\n * This can happen if the client has no pending mutations and has not been\n * used for a while (e.g. the client's tab has been hidden for a long time).\n * - the zero-cache fails to find the server side synchronization state for\n * this client.\n *\n * The default behavior is to reload the page (using `location.reload()`).\n * Provide your own function to prevent the page from reloading automatically.\n */\n onClientStateNotFound?: (() => void) | undefined;\n\n /**\n * The number of milliseconds to wait before disconnecting a Zero\n * instance whose tab has become hidden.\n *\n * Instances in hidden tabs are disconnected to save resources.\n *\n * Default is 5 minutes.\n */\n hiddenTabDisconnectDelay?: number | undefined;\n\n /**\n * The number of milliseconds to wait before disconnecting a Zero\n * instance when the connection to the server has timed out.\n *\n * Default is 1 minute.\n */\n disconnectTimeoutMs?: number | undefined;\n\n /**\n * The timeout in milliseconds for ping operations. This value is used for:\n * - How long to wait in idle before sending a ping to the server\n * - How long to wait for a pong response after sending a ping\n *\n * Total time to detect a dead connection is 2 × pingTimeoutMs.\n *\n * Default is 5_000.\n */\n pingTimeoutMs?: number | undefined;\n\n /**\n * Determines what kind of storage implementation to use on the client.\n *\n * Defaults to `'idb'` which means that Zero uses an IndexedDB storage\n * implementation. This allows the data to be persisted on the client and\n * enables faster syncs between application restarts.\n *\n * By setting this to `'mem'`, Zero uses an in memory storage and\n * the data is not persisted on the client.\n *\n * You can also set this to a function that is used to create new KV stores,\n * allowing a custom implementation of the underlying storage layer.\n */\n kvStore?: 'mem' | 'idb' | StoreProvider | undefined;\n\n /**\n * The maximum number of bytes to allow in a single header.\n *\n * Zero adds some extra information to headers on initialization if possible.\n * This speeds up data synchronization. This number should be kept less than\n * or equal to the maximum header size allowed by the zero-cache and any load\n * balancers.\n *\n * Default value: 8kb.\n */\n maxHeaderLength?: number | undefined;\n\n /**\n * The maximum amount of milliseconds to wait for a materialization to\n * complete (including network/server time) before printing a warning to the\n * console.\n *\n * Default value: 5_000.\n */\n slowMaterializeThreshold?: number | undefined;\n\n /**\n * UI rendering libraries will often provide a utility for batching multiple\n * state updates into a single render. Some examples are React's\n * `unstable_batchedUpdates`, and solid-js's `batch`.\n *\n * This option enables integrating these batch utilities with Zero.\n *\n * When `batchViewUpdates` is provided, Zero will call it whenever\n * it updates query view state with an `applyViewUpdates` function\n * that performs the actual state updates.\n *\n * Zero updates query view state when:\n * 1. creating a new view\n * 2. updating all existing queries' views to a new consistent state\n *\n * When creating a new view, that single view's creation will be wrapped\n * in a `batchViewUpdates` call.\n *\n * When updating existing queries, all queries will be updated in a single\n * `batchViewUpdates` call, so that the transition to the new consistent\n * state can be done in a single render.\n *\n * Implementations must always call `applyViewUpdates` synchronously.\n */\n batchViewUpdates?: ((applyViewUpdates: () => void) => void) | undefined;\n\n /**\n * The maximum number of recent queries, no longer subscribed to by a preload\n * or view, to continue syncing.\n *\n * Defaults is 0.\n *\n * @deprecated Use ttl instead\n */\n maxRecentQueries?: number | undefined;\n\n /**\n * Changes to queries are sent to server in batches. This option controls\n * the number of milliseconds to wait before sending the next batch.\n *\n * Defaults is 10.\n */\n queryChangeThrottleMs?: number | undefined;\n\n /**\n * Context is passed to queries when they are executed.\n */\n context?: C | undefined;\n} & (unknown extends DefaultContext\n ? {}\n : {\n context: C;\n });\n\n/**\n * @deprecated Use {@link ZeroOptions} instead.\n */\nexport type ZeroAdvancedOptions<\n S extends BaseDefaultSchema,\n MD extends CustomMutatorDefs | undefined,\n Context extends BaseDefaultContext,\n> = ZeroOptions<S, MD, Context>;\n\ntype UpdateNeededReasonBase = {\n message?: string;\n};\n\nexport type UpdateNeededReason =\n | ({type: UpdateNeededReasonType.NewClientGroup} & UpdateNeededReasonBase)\n | ({\n type: UpdateNeededReasonType.VersionNotSupported;\n } & UpdateNeededReasonBase)\n | ({\n type: UpdateNeededReasonType.SchemaVersionNotSupported;\n } & UpdateNeededReasonBase);\n\nexport const updateNeededReasonTypeSchema: v.Type<UpdateNeededReason['type']> =\n v.literalUnion(\n UpdateNeededReasonType.NewClientGroup,\n UpdateNeededReasonType.VersionNotSupported,\n UpdateNeededReasonType.SchemaVersionNotSupported,\n );\n"],"mappings":";;;AA8XA,IAAa,+BACX,aACE,gBACA,qBACA,0BACD"}
1
+ {"version":3,"file":"options.js","names":[],"sources":["../../../../../zero-client/src/client/options.ts"],"sourcesContent":["import type {LogLevel} from '@rocicorp/logger';\nimport type {StoreProvider} from '../../../replicache/src/kv/store.ts';\nimport * as v from '../../../shared/src/valita.ts';\nimport type {\n BaseDefaultContext,\n BaseDefaultSchema,\n DefaultContext,\n DefaultSchema,\n} from '../../../zero-types/src/default-types.ts';\nimport type {AnyMutatorRegistry} from '../../../zql/src/mutate/mutator-registry.ts';\nimport type {CustomMutatorDefs} from './custom.ts';\nimport {UpdateNeededReasonType} from './update-needed-reason-type.ts';\n\n/**\n * Configuration for {@linkcode Zero}.\n */\nexport type ZeroOptions<\n S extends BaseDefaultSchema = DefaultSchema,\n MD extends CustomMutatorDefs | undefined = undefined,\n C extends BaseDefaultContext = DefaultContext,\n> = {\n /**\n * URL to the zero-cache. This can be a simple hostname, e.g.\n * - \"https://myapp-myteam.zero.ms\"\n * or a prefix with a single path component, e.g.\n * - \"https://myapp-myteam.zero.ms/zero\"\n * - \"https://myapp-myteam.zero.ms/db\"\n *\n * The latter is useful for configuring routing rules (e.g. \"/zero/\\*\") when\n * the zero-cache is hosted on the same domain as the application. **Note that\n * only a single path segment is allowed (e.g. it cannot be \"/proxy/zero/\\*\")**.\n */\n cacheURL?: string | null | undefined;\n\n /**\n * @deprecated Use {@linkcode cacheURL} instead.\n */\n server?: string | null | undefined;\n\n /**\n * A token to identify and authenticate the user.\n *\n * Set `auth` to `null` or `undefined` if there is no logged in user.\n *\n * The call to `connect` is handled automatically by the ZeroProvider component\n * for React and SolidJS when the `auth` prop changes.\n *\n * Transitions between authenticated and logged-out states recreate the Zero\n * instance instead.\n *\n * When `auth` changes while connected, Zero refreshes server-side auth context\n * and re-transforms queries without reconnecting.\n *\n * When a 401 or 403 HTTP status code is received from your server, Zero will\n * transition to the `needs-auth` connection state. The app should call\n * `zero.connection.connect({auth: newToken})` with a new token to reconnect.\n */\n auth?: string | null | undefined;\n\n /**\n * A unique identifier for the user.\n *\n * Omit this, or set to `null`, for logged-out clients.\n *\n * Each userID gets its own client-side storage so that the app can switch\n * between users without losing state.\n */\n userID?: string | null | undefined;\n\n /**\n * Distinguishes the storage used by this Zero instance from that of other\n * instances with the same userID. Useful in the case where the app wants to\n * have multiple Zero instances for the same user for different parts of the\n * app.\n */\n storageKey?: string | undefined;\n\n /**\n * Determines the level of detail at which Zero logs messages about\n * its operation. Messages are logged to the `console`.\n *\n * When this is set to `'debug'`, `'info'` and `'error'` messages are also\n * logged. When set to `'info'`, `'info'` and `'error'` but not\n * `'debug'` messages are logged. When set to `'error'` only `'error'`\n * messages are logged.\n *\n * Default is `'error'`.\n */\n logLevel?: LogLevel | undefined;\n\n /**\n * This defines the schema of the tables used in Zero and their relationships\n * to one another.\n */\n schema: S;\n\n /**\n * `mutators` is a map of custom mutator definitions. The keys are\n * namespaces or names of the mutators. The values are the mutator\n * implementations. Client side mutators must be idempotent as a\n * mutation can be rebased multiple times when folding in authoritative\n * changes from the server to the client.\n *\n * Define mutators using the `defineMutator` function to create type-safe,\n * parameterized mutations. Mutators can be top-level or grouped in namespaces.\n *\n * @example\n * ```ts\n * import {defineMutator} from '@rocicorp/zero';\n *\n * const z = new Zero({\n * schema,\n * userID,\n * mutators: {\n * // Top-level mutator\n * increment: defineMutator(({tx, args}: {tx: Transaction<Schema>, args: {id: string}}) =>\n * tx.mutate.counter.update({id: args.id, value: tx.query.counter.where('id', '=', args.id).value + 1})\n * ),\n * // Namespace with multiple mutators\n * issues: {\n * create: defineMutator(({tx, args}: {tx: Transaction<Schema>, args: {title: string}}) =>\n * tx.mutate.issues.insert({id: nanoid(), title: args.title, status: 'open'})\n * ),\n * close: defineMutator(({tx, args}: {tx: Transaction<Schema>, args: {id: string}}) =>\n * tx.mutate.issues.update({id: args.id, status: 'closed'})\n * ),\n * },\n * },\n * });\n *\n * // Usage\n * await z.mutate.increment({id: 'counter-1'}).client;\n * await z.mutate.issues.create({title: 'New issue'}).client;\n * await z.mutate.issues.close({id: 'issue-123'}).client;\n * ```\n */\n mutators?: MD extends CustomMutatorDefs ? MD : AnyMutatorRegistry | undefined;\n\n /**\n * Custom URL for mutation requests sent to your API server.\n * If not provided, uses the default configured in zero-cache.\n */\n mutateURL?: string | undefined;\n\n /**\n * Custom headers to include in mutation requests sent to your API server.\n * These headers are passed through zero-cache to the mutate endpoint.\n */\n mutateHeaders?: Record<string, string> | undefined;\n\n /**\n * Custom URL for query requests sent to your API server.\n * If not provided, uses the default configured in zero-cache.\n *\n * @deprecated Use {@linkcode queryURL} instead.\n */\n getQueriesURL?: string | undefined;\n\n /**\n * Custom URL for query requests sent to your API server.\n * If not provided, uses the default configured in zero-cache.\n */\n queryURL?: string | undefined;\n\n /**\n * Custom headers to include in query requests sent to your API server.\n * These headers are passed through zero-cache to the query endpoint.\n */\n queryHeaders?: Record<string, string> | undefined;\n\n /**\n * Optional callback that returns a W3C `traceparent` header value for\n * distributed tracing. Called before sending WebSocket messages that\n * trigger API server calls (`push`, `changeDesiredQueries`,\n * `initConnection`).\n *\n * This enables end-to-end trace correlation from your frontend through\n * zero-cache to your API server.\n *\n * @example\n * ```ts\n * import {propagation, context} from '@opentelemetry/api';\n *\n * new Zero({\n * getTraceparent: () => {\n * const carrier: Record<string, string> = {};\n * propagation.inject(context.active(), carrier);\n * return carrier.traceparent;\n * },\n * });\n * ```\n */\n getTraceparent?: (() => string | undefined) | undefined;\n\n /**\n * `onOnlineChange` is called when the Zero instance's online status changes.\n *\n * @deprecated Use {@linkcode Connection.state.subscribe} on the Zero instance instead. e.g.\n * ```ts\n * const zero = new Zero({...});\n * zero.connection.state.subscribe((state) => {\n * console.log('Connection state:', state.name);\n * });\n * ```\n *\n * Or use a hook like {@linkcode useConnectionState} to subscribe to state changes.\n */\n onOnlineChange?: ((online: boolean) => void) | undefined;\n\n /**\n * `onUpdateNeeded` is called when a client code update is needed.\n *\n * See {@link UpdateNeededReason} for why updates can be needed.\n *\n * The default behavior is to reload the page (using `location.reload()`).\n * Provide your own function to prevent the page from\n * reloading automatically. You may want to display a toast to inform the end\n * user there is a new version of your app available and prompt them to\n * refresh.\n */\n onUpdateNeeded?: ((reason: UpdateNeededReason) => void) | undefined;\n\n /**\n * `onClientStateNotFound` is called when this client is no longer able\n * to sync with the zero-cache due to missing synchronization state. This\n * can be because:\n * - the local persistent synchronization state has been garbage collected.\n * This can happen if the client has no pending mutations and has not been\n * used for a while (e.g. the client's tab has been hidden for a long time).\n * - the zero-cache fails to find the server side synchronization state for\n * this client.\n *\n * The default behavior is to reload the page (using `location.reload()`).\n * Provide your own function to prevent the page from reloading automatically.\n */\n onClientStateNotFound?: (() => void) | undefined;\n\n /**\n * The number of milliseconds to wait before disconnecting a Zero\n * instance whose tab has become hidden.\n *\n * Instances in hidden tabs are disconnected to save resources.\n *\n * Default is 5 minutes.\n */\n hiddenTabDisconnectDelay?: number | undefined;\n\n /**\n * The number of milliseconds to wait before disconnecting a Zero\n * instance when the connection to the server has timed out.\n *\n * Default is 1 minute.\n */\n disconnectTimeoutMs?: number | undefined;\n\n /**\n * The timeout in milliseconds for ping operations. This value is used for:\n * - How long to wait in idle before sending a ping to the server\n * - How long to wait for a pong response after sending a ping\n *\n * Total time to detect a dead connection is 2 × pingTimeoutMs.\n *\n * Default is 5_000.\n */\n pingTimeoutMs?: number | undefined;\n\n /**\n * Determines what kind of storage implementation to use on the client.\n *\n * Defaults to `'idb'` which means that Zero uses an IndexedDB storage\n * implementation. This allows the data to be persisted on the client and\n * enables faster syncs between application restarts.\n *\n * By setting this to `'mem'`, Zero uses an in memory storage and\n * the data is not persisted on the client.\n *\n * You can also set this to a function that is used to create new KV stores,\n * allowing a custom implementation of the underlying storage layer.\n */\n kvStore?: 'mem' | 'idb' | StoreProvider | undefined;\n\n /**\n * The maximum number of bytes to allow in a single header.\n *\n * Zero adds some extra information to headers on initialization if possible.\n * This speeds up data synchronization. This number should be kept less than\n * or equal to the maximum header size allowed by the zero-cache and any load\n * balancers.\n *\n * Default value: 8kb.\n */\n maxHeaderLength?: number | undefined;\n\n /**\n * The maximum amount of milliseconds to wait for a materialization to\n * complete (including network/server time) before printing a warning to the\n * console.\n *\n * Default value: 5_000.\n */\n slowMaterializeThreshold?: number | undefined;\n\n /**\n * UI rendering libraries will often provide a utility for batching multiple\n * state updates into a single render. Some examples are React's\n * `unstable_batchedUpdates`, and solid-js's `batch`.\n *\n * This option enables integrating these batch utilities with Zero.\n *\n * When `batchViewUpdates` is provided, Zero will call it whenever\n * it updates query view state with an `applyViewUpdates` function\n * that performs the actual state updates.\n *\n * Zero updates query view state when:\n * 1. creating a new view\n * 2. updating all existing queries' views to a new consistent state\n *\n * When creating a new view, that single view's creation will be wrapped\n * in a `batchViewUpdates` call.\n *\n * When updating existing queries, all queries will be updated in a single\n * `batchViewUpdates` call, so that the transition to the new consistent\n * state can be done in a single render.\n *\n * Implementations must always call `applyViewUpdates` synchronously.\n */\n batchViewUpdates?: ((applyViewUpdates: () => void) => void) | undefined;\n\n /**\n * The maximum number of recent queries, no longer subscribed to by a preload\n * or view, to continue syncing.\n *\n * Defaults is 0.\n *\n * @deprecated Use ttl instead\n */\n maxRecentQueries?: number | undefined;\n\n /**\n * Changes to queries are sent to server in batches. This option controls\n * the number of milliseconds to wait before sending the next batch.\n *\n * Defaults is 10.\n */\n queryChangeThrottleMs?: number | undefined;\n\n /**\n * Context is passed to queries when they are executed.\n */\n context?: C | undefined;\n} & (unknown extends DefaultContext\n ? {}\n : {\n context: C;\n });\n\n/**\n * @deprecated Use {@link ZeroOptions} instead.\n */\nexport type ZeroAdvancedOptions<\n S extends BaseDefaultSchema,\n MD extends CustomMutatorDefs | undefined,\n Context extends BaseDefaultContext,\n> = ZeroOptions<S, MD, Context>;\n\ntype UpdateNeededReasonBase = {\n message?: string;\n};\n\nexport type UpdateNeededReason =\n | ({type: UpdateNeededReasonType.NewClientGroup} & UpdateNeededReasonBase)\n | ({\n type: UpdateNeededReasonType.VersionNotSupported;\n } & UpdateNeededReasonBase)\n | ({\n type: UpdateNeededReasonType.SchemaVersionNotSupported;\n } & UpdateNeededReasonBase);\n\nexport const updateNeededReasonTypeSchema: v.Type<UpdateNeededReason['type']> =\n v.literalUnion(\n UpdateNeededReasonType.NewClientGroup,\n UpdateNeededReasonType.VersionNotSupported,\n UpdateNeededReasonType.SchemaVersionNotSupported,\n );\n"],"mappings":";;;AA0XA,IAAa,+BACX,aACE,gBACA,qBACA,0BACD"}
@@ -2,7 +2,7 @@
2
2
  /**
3
3
  * The current version of Zero.
4
4
  */
5
- var version = "1.3.0-canary.0";
5
+ var version = "1.3.0-canary.1";
6
6
  //#endregion
7
7
  export { version };
8
8
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rocicorp/zero",
3
- "version": "1.3.0-canary.0",
3
+ "version": "1.3.0-canary.1",
4
4
  "description": "Zero is a web framework for serverless web development.",
5
5
  "author": "Rocicorp, Inc.",
6
6
  "repository": {